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

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