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

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