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

Last change on this file since 539 was 539, checked in by epyon, 8 years ago
  • temporary_proxy implemented
  • table_guard now uses temporary_proxy as main read functionality
File size: 16.2 KB
RevLine 
[395]1// Copyright (C) 2012-2015 ChaosForge Ltd
[9]2// http://chaosforge.org/
3//
[395]4// This file is part of Nova libraries.
5// For conditions of distribution and use, see copying.txt file in root folder.
[9]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"
[503]11#include "nv/lua/lua_types.hh"
[319]12#include "nv/core/logging.hh"
[368]13#include "nv/stl/string.hh"
[9]14
15using namespace nv;
16
[216]17// stack_guard
18
[403]19#define NV_LUA_ABORT( func, ... ) \
20        NV_LOG_CRITICAL( "lua::" func " : ", __VA_ARGS__ ) \
21        NV_ABORT( "lua::" func " : critical error!" )
22
23
[121]24lua::stack_guard::stack_guard( lua::state* aL )
[206]25        : L(aL), m_level( lua_gettop(aL->m_state) )
[9]26{
27
28}
29
[121]30lua::stack_guard::stack_guard( lua::state& aL )
[206]31        : L(&aL), m_level( lua_gettop(aL.m_state) )
[86]32{
33
34}
35
[9]36lua::stack_guard::~stack_guard()
37{
[206]38        lua_settop( L->m_state, m_level );
[9]39}
40
[334]41// stack_assert
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.get_raw()), m_expected( lua_gettop(aL.get_raw() ) + expected )
50{
51
52}
53
54nv::lua::stack_assert::stack_assert( lua_State* aL, int expected )
55        : L(aL), m_expected( lua_gettop(aL) + expected )
56{
57
58}
59
60lua::stack_assert::~stack_assert()
61{
62        NV_ASSERT( lua_gettop(L) == m_expected, "Lua stack corruption detected!" );
63}
64
65
[216]66// state_wrapper
67
68void nv::lua::state_wrapper::push_global_table()
[9]69{
[490]70        nlua_pushglobaltable( m_state );
[206]71}
72
[216]73void nv::lua::state_wrapper::pop_global_table()
[206]74{
[216]75        lua_replace( m_state, -2 );
[9]76}
77
[216]78void lua::state_wrapper::call_get()
[9]79{
[216]80        lua_gettable( m_state, -2 );
[9]81}
82
[216]83void lua::state_wrapper::call_get_raw()
[9]84{
[216]85        lua_rawget( m_state, -2 );
[9]86}
87
[399]88void lua::state_wrapper::register_native_function( lfunction f, string_view name )
[9]89{
[216]90        if ( m_global ) push_global_table();
91        lua_pushcfunction( m_state, f );
[360]92        lua_setfield( m_state, -2, name.data() );
[216]93        if ( m_global ) pop_global_table();
[9]94}
95
[216]96lua::state_wrapper::~state_wrapper()
[9]97{
[216]98        if (m_owner)
[9]99        {
[216]100                lua_close( m_state );
[9]101        }
102}
103
[216]104bool nv::lua::state_wrapper::is_defined( const path& p, bool global )
[9]105{
[216]106        if ( !p.resolve( m_state, global ) )
[9]107        {
108                return false;
109        }
[216]110        bool result = !lua_isnil( m_state, -1 );
111        lua_pop( m_state, 1 );
112        return result;
[9]113}
114
[216]115bool nv::lua::state_wrapper::push_function( const path& p, bool global )
[9]116{
[216]117        if ( !p.resolve( m_state, global ) )
[9]118        {
[440]119                NV_LOG_ERROR( "Lua error : not a valid path - ", p.to_string() );
[9]120                return false;
121        }
122
[216]123        if ( !lua_isfunction( m_state, -1 ) )
[9]124        {
[206]125                lua_pop( m_state, 1 );
[440]126                NV_LOG_ERROR( "Lua error : not a valid function - ", p.to_string() );
[216]127                return false;
[9]128        }
[216]129        return true;
[9]130}
131
[216]132int nv::lua::state_wrapper::call_function( int nargs, int nresults )
[9]133{
[216]134        int status = lua_pcall( m_state, nargs, nresults, 0 );
135        if ( status != 0 )
[9]136        {
[437]137                NV_LOG_ERROR( "Lua error : ", nlua_tostringview( m_state, -1 ) );
[216]138                lua_pop( m_state, 1 );
[9]139        }
[216]140        return status;
[9]141}
142
[216]143// table_guard
[9]144
[181]145lua::table_guard::table_guard( lua::state* lstate, const path& p, bool global )
[503]146        : state_wrapper( lstate->get_raw(), lstate->m_lua_types, false ), m_parent( lstate ), m_level(0)
[9]147{
[206]148        m_global = false;
149        m_level  = lua_gettop( m_state );
[305]150        if ( !p.resolve( m_state, global ) || lua_type(m_state, -1) != LUA_TTABLE )
[181]151        {
[365]152                NV_LOG_ERROR( "Could not resolve table!" );
[181]153                // TODO : error handling
154        }
[9]155}
156
[181]157lua::table_guard::table_guard( const table_guard& parent, const path& p )
[503]158        : state_wrapper( parent.m_state, parent.m_lua_types, false ), m_parent( parent.m_parent ), m_level(0)
[9]159{
[206]160        m_global = false;
161        m_level  = lua_gettop( m_state );
[305]162        if ( !p.resolve( m_state, false ) || lua_type(m_state, -1) != LUA_TTABLE )
[181]163        {
[365]164                NV_LOG_ERROR( "Could not resolve table!" );
[181]165                // TODO : error handling
166        }
[9]167}
168
[216]169lua::table_guard::~table_guard()
170{
171        lua_settop( m_state, m_level );
172}
173
[533]174nv::uint32 lua::table_guard::get_size()
[188]175{
[490]176        return nlua_rawlen( m_state, -1 );
[188]177}
178
[399]179bool lua::table_guard::has_field( string_view element )
[9]180{
[360]181        lua_getfield( m_state, -1, element.data() );
[288]182        bool result = !( lua_isnil( m_state, -1 ) );
[206]183        lua_pop( m_state, 1 );
[9]184        return result;
185}
186
[539]187const nv::lua::temporary_proxy nv::lua::table_guard::operator[]( const string_view& key ) const
[426]188{
[539]189        lua_getfield( m_state, -1, key.data() );
190        return temporary_proxy( m_parent );
[426]191}
192
[539]193const nv::lua::temporary_proxy nv::lua::table_guard::operator[]( sint32 key ) const
[431]194{
[539]195        lua_rawgeti( m_state, -1, key );
196        return temporary_proxy( m_parent );
[431]197}
198
[503]199bool nv::lua::table_guard::read( const string_view& element, const type_entry* entry, void* object )
200{
201        NV_ASSERT_ALWAYS( m_lua_types->get_type_database() == entry->type_db, "Type database mismatch between Lua and entry!" );
202        lua_getfield( m_state, -1, element.data() );
203        if ( lua_type( m_state, -1 ) != LUA_TTABLE )
204        {
205                lua_pop( m_state, 1 );
206                return false;
207        }
208        if ( !nv::lua::read_rtti_type( m_parent, entry, object, -1 ) )
209        {
210                lua_pop( m_state, 1 );
211                return false;
212        }
213        lua_pop( m_state, 1 );
214        return true;
215}
216
[216]217// state
218
[503]219lua::state::state( lua_State* state, type_database* types )
220        : state_wrapper( state, new type_data( types ), false )
[185]221{
[216]222
[185]223}
224
[503]225lua::state::state( bool load_libs /*= false*/, type_database* types )
226        : state_wrapper( nullptr, new type_data( types ), true )
[185]227{
[216]228        load_lua_library();
229        m_owner = true;
230        m_state = luaL_newstate( );
231
232        lua_pushcfunction(m_state, luaopen_base);
[490]233        lua_pushliteral(m_state, "");
[216]234        lua_call(m_state, 1, 0);
235
[333]236        {
237                // Preregister 8 references for Handle registry
238                lua_newtable(m_state);
239                NV_ASSERT( luaL_ref( m_state, LUA_REGISTRYINDEX ) == 1, "First reference not 1!" );
240                for ( uint32 i = 1; i < 8; ++i )
241                {
242                        lua_newtable(m_state);
243                        luaL_ref( m_state, LUA_REGISTRYINDEX );
244                }
245        }
246
[216]247        if ( load_libs )
248        {
249                stack_guard guard( this );
250                static const luaL_Reg lualibs[] =
251                {
252                        { "string", luaopen_string },
253                        { "table",  luaopen_table },
254                        { "math",   luaopen_math },
255                        { NULL, NULL}
256                };
257                const luaL_Reg *lib = lualibs;
258                for(; lib->func != NULL; lib++)
259                {
[228]260                        lua_pushcfunction( m_state, lib->func );
261                        lua_call(m_state, 0, 1);
262                        lua_setglobal( m_state, lib->name );
[216]263                }
[217]264                register_nova( this );
[216]265        }
266
[365]267        NV_LOG_TRACE( "Lua state created" );
[185]268}
269
[399]270int lua::state::load_string( string_view code, string_view name )
[188]271{
[365]272        NV_LOG_TRACE( "Loading Lua string '", name, "'");
[360]273        return luaL_loadbuffer( m_state, code.data(), code.length(), name.data() );
[188]274}
[185]275
[399]276int lua::state::load_file( string_view filename )
[216]277{
[365]278        NV_LOG_NOTICE( "Loading Lua file '", filename, "'");
[360]279        return luaL_loadfile( m_state, filename.data() );
[216]280}
[212]281
[399]282bool lua::state::do_string( string_view code, string_view name, int rvalues )
[212]283{
[216]284        lua::stack_guard( this );
285        int result = load_string(code,name);
286        if (result)
287        {
[437]288                NV_LOG_WARNING( "Failed to load string ", name, ": ", nlua_tostringview(m_state, -1));
[216]289                return false;
290        }
291        return do_current( name, rvalues ) == 0;
[212]292}
293
[399]294bool lua::state::do_file( string_view filename )
[216]295{
296        lua::stack_guard( this );
297        int result = load_file(filename);
298        if (result)
299        {
[437]300                NV_LOG_WARNING( "Failed to open file ", filename, ": ", nlua_tostringview( m_state, -1 ) );
[216]301                return false;
302        }
303        return do_current( filename ) == 0;
304}
305
[399]306int lua::state::do_current( string_view name, int rvalues )
[216]307{
308        int result = lua_pcall(m_state, 0, rvalues, 0);
309        if (result)
310        {
[437]311                NV_LOG_WARNING( "Failed to run script ", name, ": ", nlua_tostringview( m_state, -1 ) );
[216]312                lua_pop( m_state, 1 );
313        }
314        return result;
315}
316
317int lua::state::get_stack_size()
318{
319        return lua_gettop( m_state );
320}
321
[9]322void lua::state::log_stack()
323{
[206]324        int top = lua_gettop(m_state);
[365]325        NV_LOG_DEBUG( "Stack dump (", top, ")");
[9]326        for ( int i = 0; i < top; ++i )
327        {
[437]328                NV_LOG_DEBUG( "#", i+1, " - ", lua_typename(m_state, lua_type(m_state, i+1) ), " = ", nlua_typecontent(m_state, i+1) );
[9]329        }
330}
331
332lua_State* lua::state::get_raw()
333{
[206]334        return m_state;
[9]335}
336
[399]337lua::ref lua::state::register_object( void* o, string_view lua_name )
[77]338{
[265]339        if ( o == nullptr ) return lua::ref( lua::ref::none );
[77]340        stack_guard guard( this );
[360]341        lua_getglobal( m_state, lua_name.data() );
[206]342        if ( lua_isnil( m_state, -1 ) )
[77]343        {
[403]344                NV_LUA_ABORT( "state::register_object", lua_name, " type not registered!" );
[77]345        }
346        deep_pointer_copy( -1, o );
[265]347        return lua::ref( luaL_ref( m_state, LUA_REGISTRYINDEX ) );
[77]348}
[9]349
[399]350lua::ref lua::state::register_proto( string_view id, string_view storage )
[217]351{
352        stack_guard guard( this );
[360]353        lua_getglobal( m_state, storage.data() );
[217]354        if ( lua_isnil( m_state, -1 ) )
355        {
[403]356                NV_LUA_ABORT( "state::register_proto", "\"", storage, "\" storage not registered!" );
[217]357        }
[360]358        lua_getfield( m_state, -1, id.data() );
[217]359        if ( lua_isnil( m_state, -1 ) )
360        {
[403]361                NV_LUA_ABORT( "state::register_proto", "\"", id, "\" not found in \"", storage, "\"!" );
[217]362        }
[265]363        return lua::ref( luaL_ref( m_state, LUA_REGISTRYINDEX ) );
[217]364}
365
[399]366void lua::state::register_native_object_method( string_view lua_name, string_view name, lfunction f )
[212]367{
368        stack_guard guard( this );
[360]369        lua_getglobal( m_state, lua_name.data() );
[212]370        if ( lua_isnil( m_state, -1 ) )
371        {
[403]372                NV_LUA_ABORT( "state::register_native_object_method", "\"", lua_name, "\" type not registered!" );
[212]373        }
374        lua_pushcfunction( m_state, f );
[360]375        lua_setfield( m_state, -2, name.data() );
[212]376}
377
[265]378void lua::state::unregister_object( ref object_index )
[77]379{
[265]380        if ( !object_index.is_valid() ) return;
[77]381        stack_guard guard( this );
[265]382        lua_rawgeti( m_state, LUA_REGISTRYINDEX, object_index.get() );
[360]383        lua_pushliteral( m_state, "__ptr" );
[206]384        lua_pushboolean( m_state, false );
385        lua_rawset( m_state, -3 );
386        lua_pop( m_state, 1 );
[265]387        luaL_unref( m_state, LUA_REGISTRYINDEX, object_index.get() );
[77]388}
389
[256]390
[77]391void lua::state::deep_pointer_copy( int index, void* obj )
392{
[490]393        index = nlua_absindex( m_state, index );
[206]394        lua_newtable( m_state );
395        lua_pushnil( m_state );
[77]396        bool has_functions = false;
397        bool has_metatable = false;
398
[206]399        while ( lua_next( m_state, index ) != 0 )
[77]400        {
[206]401                if ( lua_isfunction( m_state, -1 ) )
[77]402                        has_functions = true;
[206]403                else if ( lua_istable( m_state, -1 ) )
[77]404                {
405                        deep_pointer_copy( -1, obj );
[206]406                        lua_insert( m_state, -2 );
407                        lua_pop( m_state, 1 );
[77]408                }
[206]409                lua_pushvalue( m_state, -2 );
410                lua_insert( m_state, -2 );
411                lua_settable( m_state, -4 );
[77]412        }
413
[206]414        if ( lua_getmetatable( m_state, -2 ) )
[77]415        {
[206]416                lua_setmetatable( m_state, -2 );
[77]417                has_metatable = true;
418        }
419
420        if ( has_functions || has_metatable )
421        {
[403]422                lua_pushliteral( m_state, "__ptr" );
[206]423                lua_pushlightuserdata( m_state, obj );
424                lua_rawset( m_state, -3 );
[77]425        }
426}
[163]427
[399]428void nv::lua::state::store_metadata( ref object_index, string_view metaname, void* pointer )
[163]429{
[265]430        if ( !object_index.is_valid() ) return;
431        lua_rawgeti( m_state, LUA_REGISTRYINDEX, object_index.get() );
[437]432        nlua_pushstringview( m_state, metaname );
[206]433        lua_pushlightuserdata( m_state, pointer );
434        lua_rawset( m_state, -3 );
435        lua_pop( m_state, 1 );
436}
[188]437
[399]438void nv::lua::state::register_enum( string_view name, int value )
[215]439{
[262]440        lua_pushinteger( m_state, value );
[360]441        lua_setglobal( m_state, name.data() );
[215]442}
443
[511]444void nv::lua::state::register_enum( const type_entry* type )
445{
446        NV_ASSERT_ALWAYS( type, "type not found!" );
447        NV_ASSERT_ALWAYS( !type->enum_list.empty(), "type not enum!" );
448        type_database* db = type->type_db;
449        for ( auto e : type->enum_list )
450        {
451                lua_pushinteger( m_state, e.value );
452                lua_setglobal( m_state, db->resolve_name( e.name ).data() );
453        }
454}
455
[503]456void nv::lua::state::register_rtti_type( thash64 tid, lua_rtti_push_function p, lua_rtti_read_function r )
457{
458        m_lua_types->insert( tid, p, r );
459}
460
[399]461nv::lua::ref nv::lua::state::register_handle_component_impl( string_view id, bool empty )
[341]462{
463        int args = empty ? 1 : 2;
464        NV_LUA_STACK_ASSERT( m_state, -args );
465
466        if ( lua_isnil( m_state, -1 ) || (!empty && lua_isnil( m_state, -2 )) )
467        {
468                lua_pop( m_state, args );
469                return ref();
470        }
471        if (empty)
472                lua_createtable( m_state, 0, 0 );
473        else
474                nlua_deepcopy( m_state, -2 );
[437]475        nlua_pushstringview( m_state, id );
[341]476        lua_pushvalue( m_state, -2 );
477        lua_rawset( m_state, -4 );
478        lua_replace( m_state, -2 );
479        ref result = lua::ref( luaL_ref( m_state, LUA_REGISTRYINDEX ) );
480        if (!empty) lua_pop( m_state, 1 );
481        return result;
482}
483
[399]484void nv::lua::state::unregister_handle_component_impl( string_view id )
[341]485{
486        NV_LUA_STACK_ASSERT( m_state, -1 );
487
488        if ( lua_isnil( m_state, -1 ) )
489        {
490                lua_pop( m_state, 1 );
491                return;
492        }
[437]493        nlua_pushstringview( m_state, id );
[341]494        lua_pushnil( m_state );
495        lua_rawset( m_state, -3 );
496        lua_pop( m_state, 1 );
497}
498
[399]499void nv::lua::state::register_singleton( string_view name, void* o )
[341]500{
501        if ( o == nullptr ) return;
502        stack_guard guard( this );
[360]503        lua_getglobal( m_state, name.data() );
[341]504        if ( lua_isnil( m_state, -1 ) )
505        {
[403]506                NV_LUA_ABORT( "state::register_singleton", "\"", name, "\" type not registered!" );
[341]507        }
508        deep_pointer_copy( -1, o );
[360]509        lua_setglobal( m_state, name.data() );
[341]510}
511
[503]512nv::lua::state::~state()
513{
514        delete m_lua_types;
515        m_lua_types = nullptr;
516}
517
518template < typename T >
519void nlua_rtti_signed_push( nv::lua::state* state, const type_entry*, void* object )
520{
521        T* value = reinterpret_cast<T*>( object );
522        lua_pushinteger( state->get_raw(), lua_Integer( *value ) );
523}
524
525template < typename T >
526void nlua_rtti_unsigned_push( nv::lua::state* state, const type_entry*, void* object )
527{
528        T* value = reinterpret_cast<T*>( object );
529        lua_pushinteger( state->get_raw(), lua_Unsigned( *value ) );
530}
531
532template < typename T >
533void nlua_rtti_floating_push( nv::lua::state* state, const type_entry*, void* object )
534{
535        T* value = reinterpret_cast< T* >( object );
536        lua_pushnumber( state->get_raw(), lua_Number( *value ) );
537}
538
539static void nlua_rtti_boolean_push( nv::lua::state* state, const type_entry*, void* object )
540{
541        bool* value = reinterpret_cast<bool*>( object );
542        lua_pushboolean( state->get_raw(), *value );
543}
544
545template < typename T >
546bool nlua_rtti_signed_read( nv::lua::state* state, const type_entry*, void* object, int index )
547{
548        T* value = reinterpret_cast<T*>( object );
549        if ( lua_type( state->get_raw(), index ) == LUA_TNUMBER )
550        {
551                *value = T( lua_tointeger( state->get_raw(), index ) );
552                return true;
553        }
554        return false;
555}
556
557template < typename T >
558bool nlua_rtti_unsigned_read( nv::lua::state* state, const type_entry*, void* object, int index )
559{
560        T* value = reinterpret_cast<T*>( object );
561        if ( lua_type( state->get_raw(), index ) == LUA_TNUMBER )
562        {
563                *value = T( lua_tointeger( state->get_raw(), index ) );
564                return true;
565        }
566        return false;
567}
568
569template < typename T >
570bool nlua_rtti_floating_read( nv::lua::state* state, const type_entry*, void* object, int index )
571{
572        T* value = reinterpret_cast<T*>( object );
573        if ( lua_type( state->get_raw(), index ) == LUA_TNUMBER )
574        {
575                *value = T( lua_tonumber( state->get_raw(), index ) );
576                return true;
577        }
578        return false;
579}
580
581static bool nlua_rtti_boolean_read( nv::lua::state* state, const type_entry*, void* object, int index )
582{
583        bool* value = reinterpret_cast<bool*>( object );
584        if ( lua_type( state->get_raw(), index ) == LUA_TBOOLEAN )
585        {
[534]586                *value = lua_toboolean( state->get_raw(), index ) != 0;
[503]587                return true;
588        }
589        return false;
590}
591
592
593void nv::lua::type_data::insert( thash64 tid, lua_rtti_push_function p, lua_rtti_read_function r )
594{
595        m_type_read.assign( tid, r );
596        m_type_push.assign( tid, p );
597}
598
599void nv::lua::type_data::register_standard_types()
600{
601        insert<bool>( nlua_rtti_boolean_push, nlua_rtti_boolean_read );
602        insert<nv::sint8> ( nlua_rtti_signed_push<nv::sint8>,    nlua_rtti_signed_read<nv::sint8> );
603        insert<nv::sint16>( nlua_rtti_signed_push<nv::sint16>,   nlua_rtti_signed_read<nv::sint16> );
604        insert<nv::sint32>( nlua_rtti_signed_push<nv::sint32>,   nlua_rtti_signed_read<nv::sint32> );
605        insert<nv::uint8> ( nlua_rtti_unsigned_push<nv::uint8>,  nlua_rtti_unsigned_read<nv::uint8> );
606        insert<nv::uint16>( nlua_rtti_unsigned_push<nv::uint16>, nlua_rtti_unsigned_read<nv::uint16> );
607        insert<nv::uint32>( nlua_rtti_unsigned_push<nv::uint32>, nlua_rtti_unsigned_read<nv::uint32> );
608        insert<nv::f32>   ( nlua_rtti_floating_push<nv::f32>,    nlua_rtti_floating_read<nv::f32> );
609        insert<nv::f64>   ( nlua_rtti_floating_push<nv::f64>,    nlua_rtti_floating_read<nv::f64> );
610//      insert<nv::sint64>( nlua_rtti_floating_push<nv::sint64>, nlua_rtti_floating_read<nv::sint64> );
611//      insert<nv::uint64>( nlua_rtti_floating_push<nv::uint64>, nlua_rtti_floating_read<nv::uint64> );
612}
[538]613
Note: See TracBrowser for help on using the repository browser.