source: trunk/src/lua/lua_state.cc @ 336

Last change on this file since 336 was 334, checked in by epyon, 11 years ago
  • added lua::stack_assert - will come in use later
File size: 13.3 KB
RevLine 
[319]1// Copyright (C) 2012-2014 ChaosForge Ltd
[9]2// http://chaosforge.org/
3//
4// This file is part of NV Libraries.
5// For conditions of distribution and use, see copyright notice in nv.hh
6
7#include "nv/lua/lua_state.hh"
8
[51]9#include "nv/lua/lua_raw.hh"
[217]10#include "nv/lua/lua_nova.hh"
[319]11#include "nv/core/logging.hh"
12#include "nv/core/string.hh"
[9]13
14using namespace nv;
15
[216]16// stack_guard
17
[121]18lua::stack_guard::stack_guard( lua::state* aL )
[206]19        : L(aL), m_level( lua_gettop(aL->m_state) )
[9]20{
21
22}
23
[121]24lua::stack_guard::stack_guard( lua::state& aL )
[206]25        : L(&aL), m_level( lua_gettop(aL.m_state) )
[86]26{
27
28}
29
[9]30lua::stack_guard::~stack_guard()
31{
[206]32        lua_settop( L->m_state, m_level );
[9]33}
34
[334]35// stack_assert
36nv::lua::stack_assert::stack_assert( lua::state* aL, int expected )
37        : L(aL->get_raw()), m_expected( lua_gettop(aL->get_raw() ) + expected )
38{
39
40}
41
42nv::lua::stack_assert::stack_assert( lua::state& aL, int expected )
43        : L(aL.get_raw()), m_expected( lua_gettop(aL.get_raw() ) + expected )
44{
45
46}
47
48nv::lua::stack_assert::stack_assert( lua_State* aL, int expected )
49        : L(aL), m_expected( lua_gettop(aL) + expected )
50{
51
52}
53
54lua::stack_assert::~stack_assert()
55{
56        NV_ASSERT( lua_gettop(L) == m_expected, "Lua stack corruption detected!" );
57}
58
59
[216]60// state_wrapper
61
62void nv::lua::state_wrapper::push_global_table()
[9]63{
[216]64        lua_pushglobaltable( m_state );
[206]65}
66
[216]67void nv::lua::state_wrapper::pop_global_table()
[206]68{
[216]69        lua_replace( m_state, -2 );
[9]70}
71
[216]72void lua::state_wrapper::call_get()
[9]73{
[216]74        lua_gettable( m_state, -2 );
[9]75}
76
[216]77void lua::state_wrapper::call_get_raw()
[9]78{
[216]79        lua_rawget( m_state, -2 );
[9]80}
81
[216]82void lua::state_wrapper::register_native_function( lfunction f, const char* name )
[9]83{
[216]84        if ( m_global ) push_global_table();
85        lua_pushcfunction( m_state, f );
86        lua_setfield( m_state, -2, name );
87        if ( m_global ) pop_global_table();
[9]88}
89
[216]90lua::state_wrapper::~state_wrapper()
[9]91{
[216]92        if (m_owner)
[9]93        {
[216]94                lua_close( m_state );
[9]95        }
96}
97
[216]98bool nv::lua::state_wrapper::is_defined( const path& p, bool global )
[9]99{
[216]100        if ( !p.resolve( m_state, global ) )
[9]101        {
102                return false;
103        }
[216]104        bool result = !lua_isnil( m_state, -1 );
105        lua_pop( m_state, 1 );
106        return result;
[9]107}
108
[216]109bool nv::lua::state_wrapper::push_function( const path& p, bool global )
[9]110{
[216]111        if ( !p.resolve( m_state, global ) )
[9]112        {
[216]113                NV_LOG( LOG_ERROR, "Lua error : not a valid path - " + p.to_string() );
[9]114                return false;
115        }
116
[216]117        if ( !lua_isfunction( m_state, -1 ) )
[9]118        {
[206]119                lua_pop( m_state, 1 );
[216]120                NV_LOG( LOG_ERROR, "Lua error : not a valid function - " + p.to_string() );
121                return false;
[9]122        }
[216]123        return true;
[9]124}
125
[216]126int nv::lua::state_wrapper::call_function( int nargs, int nresults )
[9]127{
[216]128        int status = lua_pcall( m_state, nargs, nresults, 0 );
129        if ( status != 0 )
[9]130        {
[216]131                std::string error = lua_tostring( m_state, -1 );
132                lua_pop( m_state, 1 );
133                NV_LOG( LOG_ERROR, "Lua error : " << error )
[9]134        }
[216]135        return status;
[9]136}
137
[216]138// table_guard
[9]139
[181]140lua::table_guard::table_guard( lua::state* lstate, const path& p, bool global )
[206]141        : state_wrapper( lstate->get_raw(), false ), m_level(0)
[9]142{
[206]143        m_global = false;
144        m_level  = lua_gettop( m_state );
[305]145        if ( !p.resolve( m_state, global ) || lua_type(m_state, -1) != LUA_TTABLE )
[181]146        {
[305]147                NV_LOG( LOG_ERROR, "Could not resolve table!" );
[181]148                // TODO : error handling
149        }
[9]150}
151
[181]152lua::table_guard::table_guard( const table_guard& parent, const path& p )
[206]153        : state_wrapper( parent.m_state, false ), m_level(0)
[9]154{
[206]155        m_global = false;
156        m_level  = lua_gettop( m_state );
[305]157        if ( !p.resolve( m_state, false ) || lua_type(m_state, -1) != LUA_TTABLE )
[181]158        {
[305]159                NV_LOG( LOG_ERROR, "Could not resolve table!" );
[181]160                // TODO : error handling
161        }
[9]162}
163
[216]164lua::table_guard::~table_guard()
165{
166        lua_settop( m_state, m_level );
167}
168
[188]169size_t lua::table_guard::get_size()
170{
[206]171        return lua_rawlen( m_state, -1 );
[188]172}
173
[9]174bool lua::table_guard::has_field( const string& element )
175{
[206]176        lua_getfield( m_state, -1, element.c_str() );
[288]177        bool result = !( lua_isnil( m_state, -1 ) );
[206]178        lua_pop( m_state, 1 );
[9]179        return result;
180}
181
182string lua::table_guard::get_string( const string& element, const string& defval /*= "" */ )
183{
[206]184        lua_getfield( m_state, -1, element.c_str() );
185        string result( ( lua_type( m_state, -1 ) == LUA_TSTRING ) ? lua_tostring( m_state, -1 ) : defval );
186        lua_pop( m_state, 1 );
[9]187        return result;
188}
189
190char lua::table_guard::get_char( const string& element, char defval /*= "" */ )
191{
[206]192        lua_getfield( m_state, -1, element.c_str() );
193        char result = ( lua_type( m_state, -1 ) == LUA_TSTRING && lua_rawlen( m_state, -1 ) > 0 ) ? lua_tostring( m_state, -1 )[0] : defval;
194        lua_pop( m_state, 1 );
[9]195        return result;
196}
197
198int lua::table_guard::get_integer( const string& element, int defval /*= "" */ )
199{
[206]200        lua_getfield( m_state, -1, element.c_str() );
201        lua_Integer result = lua_type( m_state, -1 ) == LUA_TNUMBER ? lua_tointeger( m_state, -1 ) : defval;
202        lua_pop( m_state, 1 );
[204]203        return static_cast< int >( result );
[9]204}
205
[188]206unsigned lua::table_guard::get_unsigned( const string& element, unsigned defval /*= "" */ )
207{
[206]208        lua_getfield( m_state, -1, element.c_str() );
209        unsigned result = lua_type( m_state, -1 ) == LUA_TNUMBER ? lua_tounsigned( m_state, -1 ) : defval;
210        lua_pop( m_state, 1 );
[188]211        return result;
212}
213
[9]214double lua::table_guard::get_double( const string& element, double defval /*= "" */ )
215{
[206]216        lua_getfield( m_state, -1, element.c_str() );
217        double result = lua_type( m_state, -1 ) == LUA_TNUMBER ? lua_tonumber( m_state, -1 ) : defval;
218        lua_pop( m_state, 1 );
[9]219        return result;
220}
221
[288]222
223float nv::lua::table_guard::get_float( const std::string& element, float defval /*= 0.0 */ )
224{
225        lua_getfield( m_state, -1, element.c_str() );
226        float result = lua_type( m_state, -1 ) == LUA_TNUMBER ? (float)lua_tonumber( m_state, -1 ) : defval;
227        lua_pop( m_state, 1 );
228        return result;
229}
230
[9]231bool lua::table_guard::get_boolean( const string& element, bool defval /*= "" */ )
232{
[206]233        lua_getfield( m_state, -1, element.c_str() );
234        bool result = lua_type( m_state, -1 ) == LUA_TBOOLEAN ? lua_toboolean( m_state, -1 ) != 0 : defval;
235        lua_pop( m_state, 1 );
[9]236        return result;
237}
238
[296]239bool nv::lua::table_guard::is_table( const std::string& element )
240{
241        lua_getfield( m_state, -1, element.c_str() );
242        bool result = lua_type( m_state, -1 ) == LUA_TTABLE;
243        lua_pop( m_state, 1 );
244        return result;
245}
246
247bool nv::lua::table_guard::is_number( const std::string& element )
248{
249        lua_getfield( m_state, -1, element.c_str() );
250        bool result = lua_type( m_state, -1 ) == LUA_TNUMBER;
251        lua_pop( m_state, 1 );
252        return result;
253}
254
255bool nv::lua::table_guard::is_boolean( const std::string& element )
256{
257        lua_getfield( m_state, -1, element.c_str() );
258        bool result = lua_type( m_state, -1 ) == LUA_TBOOLEAN;
259        lua_pop( m_state, 1 );
260        return result;
261}
262
263bool nv::lua::table_guard::is_string( const std::string& element )
264{
265        lua_getfield( m_state, -1, element.c_str() );
266        bool result = lua_type( m_state, -1 ) == LUA_TSTRING;
267        lua_pop( m_state, 1 );
268        return result;
269}
270
271
[216]272// state
273
[262]274lua::state::state( lua_State* state ) : state_wrapper( state, false )
[185]275{
[216]276
[185]277}
278
[262]279lua::state::state( bool load_libs /*= false*/ ) : state_wrapper( nullptr, true )
[185]280{
[216]281        load_lua_library();
282        m_owner = true;
283        m_state = luaL_newstate( );
284
285        lua_pushcfunction(m_state, luaopen_base);
286        lua_pushliteral(m_state, LUA_TABLIBNAME);
287        lua_call(m_state, 1, 0);
288
[333]289        {
290                // Preregister 8 references for Handle registry
291                lua_newtable(m_state);
292                NV_ASSERT( luaL_ref( m_state, LUA_REGISTRYINDEX ) == 1, "First reference not 1!" );
293                for ( uint32 i = 1; i < 8; ++i )
294                {
295                        lua_newtable(m_state);
296                        luaL_ref( m_state, LUA_REGISTRYINDEX );
297                }
298        }
299
[216]300        if ( load_libs )
301        {
302                stack_guard guard( this );
303                static const luaL_Reg lualibs[] =
304                {
305                        { "string", luaopen_string },
306                        { "table",  luaopen_table },
307                        { "math",   luaopen_math },
308                        { NULL, NULL}
309                };
310                const luaL_Reg *lib = lualibs;
311                for(; lib->func != NULL; lib++)
312                {
[228]313                        lua_pushcfunction( m_state, lib->func );
314                        lua_call(m_state, 0, 1);
315                        lua_setglobal( m_state, lib->name );
[216]316                }
[217]317                register_nova( this );
[216]318        }
319
320        NV_LOG( nv::LOG_TRACE, "Lua state created" );
[185]321}
322
[216]323int lua::state::load_string( const std::string& code, const std::string& name )
[188]324{
[216]325        NV_LOG( nv::LOG_TRACE, "Loading Lua string '" << name << "'");
326        return luaL_loadbuffer( m_state, code.c_str(), code.length(), name.c_str() );
[188]327}
[185]328
[216]329int lua::state::load_stream( std::istream& stream, const std::string& name )
[206]330{
[216]331        NV_LOG( nv::LOG_NOTICE, "Loading Lua stream '" << name << "'");
332        return load_string( std::string(
333                (std::istreambuf_iterator<char>(stream)),
334                std::istreambuf_iterator<char>()), name );
[206]335}
336
[216]337int lua::state::load_file( const std::string& filename )
338{
339        NV_LOG( nv::LOG_NOTICE, "Loading Lua file '" << filename << "'");
340        return luaL_loadfile( m_state, filename.c_str() );
341}
[212]342
[216]343bool lua::state::do_string( const std::string& code, const std::string& name, int rvalues )
[212]344{
[216]345        lua::stack_guard( this );
346        int result = load_string(code,name);
347        if (result)
348        {
349                NV_LOG( nv::LOG_WARNING, "Failed to load string " << name << ": " << lua_tostring(m_state, -1));
350                return false;
351        }
352        return do_current( name, rvalues ) == 0;
[212]353}
354
[216]355bool lua::state::do_stream( std::istream& stream, const std::string& name )
356{
357        lua::stack_guard( this );
358        int result = load_stream(stream,name);
359        if (result)
360        {
361                NV_LOG( nv::LOG_WARNING, "Failed to open stream " << name << ": " << lua_tostring(m_state, -1));
362                return false;
363        }
364        return do_current( name ) == 0;
365}
366
367bool lua::state::do_file( const std::string& filename )
368{
369        lua::stack_guard( this );
370        int result = load_file(filename);
371        if (result)
372        {
373                NV_LOG( nv::LOG_WARNING, "Failed to open file " << filename << ": " << lua_tostring(m_state, -1));
374                return false;
375        }
376        return do_current( filename ) == 0;
377}
378
379int lua::state::do_current( const std::string& name, int rvalues )
380{
381        int result = lua_pcall(m_state, 0, rvalues, 0);
382        if (result)
383        {
384                NV_LOG( nv::LOG_WARNING, "Failed to run script " << name << ": " << lua_tostring(m_state, -1));
385                lua_pop( m_state, 1 );
386        }
387        return result;
388}
389
390int lua::state::get_stack_size()
391{
392        return lua_gettop( m_state );
393}
394
[9]395void lua::state::log_stack()
396{
[206]397        int top = lua_gettop(m_state);
[9]398        NV_LOG( LOG_DEBUG, "Stack dump (" << top << ")");
399        for ( int i = 0; i < top; ++i )
400        {
[206]401                NV_LOG( LOG_DEBUG, "#" << i+1 << " - " << lua_typename(m_state, lua_type(m_state, i+1) ) << " = " << nlua_typecontent(m_state, i+1) );
[9]402        }
403}
404
405lua_State* lua::state::get_raw()
406{
[206]407        return m_state;
[9]408}
409
[265]410lua::ref lua::state::register_object( void* o, const char* lua_name )
[77]411{
[265]412        if ( o == nullptr ) return lua::ref( lua::ref::none );
[77]413        stack_guard guard( this );
[206]414        lua_getglobal( m_state, lua_name );
415        if ( lua_isnil( m_state, -1 ) )
[77]416        {
[187]417                NV_THROW( runtime_error, std::string( lua_name ) + " type not registered!" );
[77]418        }
419        deep_pointer_copy( -1, o );
[265]420        return lua::ref( luaL_ref( m_state, LUA_REGISTRYINDEX ) );
[77]421}
[9]422
[265]423lua::ref lua::state::register_proto( const char* id, const char* storage )
[217]424{
425        stack_guard guard( this );
426        lua_getglobal( m_state, storage );
427        if ( lua_isnil( m_state, -1 ) )
428        {
429                NV_THROW( runtime_error, std::string( storage ) + " storage not registered!" );
430        }
[262]431        lua_getfield( m_state, -1, id );
[217]432        if ( lua_isnil( m_state, -1 ) )
433        {
[262]434                NV_THROW( runtime_error, std::string( id ) + " not found in " + std::string( storage ) + " storage!" );
[217]435        }
[265]436        return lua::ref( luaL_ref( m_state, LUA_REGISTRYINDEX ) );
[217]437}
438
[212]439void lua::state::register_native_object_method( const char* lua_name, const char* name, lfunction f )
440{
441        stack_guard guard( this );
442        lua_getglobal( m_state, lua_name );
443        if ( lua_isnil( m_state, -1 ) )
444        {
445                NV_THROW( runtime_error, std::string( lua_name ) + " type not registered!" );
446        }
447        lua_pushcfunction( m_state, f );
448        lua_setfield( m_state, -2, name );
449}
450
[265]451void lua::state::unregister_object( ref object_index )
[77]452{
[265]453        if ( !object_index.is_valid() ) return;
[77]454        stack_guard guard( this );
[265]455        lua_rawgeti( m_state, LUA_REGISTRYINDEX, object_index.get() );
[206]456        lua_pushstring( m_state, "__ptr" );
457        lua_pushboolean( m_state, false );
458        lua_rawset( m_state, -3 );
459        lua_pop( m_state, 1 );
[265]460        luaL_unref( m_state, LUA_REGISTRYINDEX, object_index.get() );
[77]461}
462
[256]463
[77]464void lua::state::deep_pointer_copy( int index, void* obj )
465{
[206]466        index = lua_absindex( m_state, index );
467        lua_newtable( m_state );
468        lua_pushnil( m_state );
[77]469        bool has_functions = false;
470        bool has_metatable = false;
471
[206]472        while ( lua_next( m_state, index ) != 0 )
[77]473        {
[206]474                if ( lua_isfunction( m_state, -1 ) )
[77]475                        has_functions = true;
[206]476                else if ( lua_istable( m_state, -1 ) )
[77]477                {
478                        deep_pointer_copy( -1, obj );
[206]479                        lua_insert( m_state, -2 );
480                        lua_pop( m_state, 1 );
[77]481                }
[206]482                lua_pushvalue( m_state, -2 );
483                lua_insert( m_state, -2 );
484                lua_settable( m_state, -4 );
[77]485        }
486
[206]487        if ( lua_getmetatable( m_state, -2 ) )
[77]488        {
[206]489                lua_setmetatable( m_state, -2 );
[77]490                has_metatable = true;
491        }
492
493        if ( has_functions || has_metatable )
494        {
[206]495                lua_pushstring( m_state, "__ptr" );
496                lua_pushlightuserdata( m_state, obj );
497                lua_rawset( m_state, -3 );
[77]498        }
499}
[163]500
[265]501void nv::lua::state::store_metadata( ref object_index, const std::string& metaname, void* pointer )
[163]502{
[265]503        if ( !object_index.is_valid() ) return;
504        lua_rawgeti( m_state, LUA_REGISTRYINDEX, object_index.get() );
[206]505        lua_pushstring( m_state, metaname.c_str() );
506        lua_pushlightuserdata( m_state, pointer );
507        lua_rawset( m_state, -3 );
508        lua_pop( m_state, 1 );
509}
[188]510
[262]511void nv::lua::state::register_enum( const char* name, int value )
[215]512{
[262]513        lua_pushinteger( m_state, value );
514        lua_setglobal( m_state, name );
[215]515}
516
Note: See TracBrowser for help on using the repository browser.