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

Last change on this file since 540 was 540, checked in by epyon, 8 years ago
  • lua::stack_proxy RTTI read support
  • missing RTTI declarations
  • new lua::table_guard syntax
File size: 16.4 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        }
[540]155        m_index = -1;
[9]156}
157
[181]158lua::table_guard::table_guard( const table_guard& parent, const path& p )
[503]159        : state_wrapper( parent.m_state, parent.m_lua_types, false ), m_parent( parent.m_parent ), m_level(0)
[9]160{
[206]161        m_global = false;
162        m_level  = lua_gettop( m_state );
[305]163        if ( !p.resolve( m_state, false ) || lua_type(m_state, -1) != LUA_TTABLE )
[181]164        {
[365]165                NV_LOG_ERROR( "Could not resolve table!" );
[181]166                // TODO : error handling
167        }
[540]168        m_index = -1;
[9]169}
170
[216]171lua::table_guard::~table_guard()
172{
[540]173        if ( m_index == -1 )
174                lua_settop( m_state, m_level );
[216]175}
176
[540]177nv::uint32 lua::table_guard::size()
[188]178{
[540]179        return nlua_rawlen( m_state, m_index );
[188]180}
181
[540]182nv::lua::table_guard::table_guard( stack_proxy& proxy )
183        : state_wrapper( *proxy.m_state, proxy.m_state->m_lua_types, false ), m_parent( proxy.m_state ), m_level( 0 )
[9]184{
[540]185        m_level = lua_gettop( m_state );
186        m_index = proxy.m_index;
[9]187}
188
[539]189const nv::lua::temporary_proxy nv::lua::table_guard::operator[]( const string_view& key ) const
[426]190{
[540]191        lua_getfield( m_state, m_index, key.data() );
[539]192        return temporary_proxy( m_parent );
[426]193}
194
[539]195const nv::lua::temporary_proxy nv::lua::table_guard::operator[]( sint32 key ) const
[431]196{
[540]197        lua_rawgeti( m_state, m_index, key );
[539]198        return temporary_proxy( m_parent );
[431]199}
200
[216]201// state
202
[503]203lua::state::state( lua_State* state, type_database* types )
204        : state_wrapper( state, new type_data( types ), false )
[185]205{
[216]206
[185]207}
208
[503]209lua::state::state( bool load_libs /*= false*/, type_database* types )
210        : state_wrapper( nullptr, new type_data( types ), true )
[185]211{
[216]212        load_lua_library();
213        m_owner = true;
214        m_state = luaL_newstate( );
215
216        lua_pushcfunction(m_state, luaopen_base);
[490]217        lua_pushliteral(m_state, "");
[216]218        lua_call(m_state, 1, 0);
219
[333]220        {
221                // Preregister 8 references for Handle registry
222                lua_newtable(m_state);
223                NV_ASSERT( luaL_ref( m_state, LUA_REGISTRYINDEX ) == 1, "First reference not 1!" );
224                for ( uint32 i = 1; i < 8; ++i )
225                {
226                        lua_newtable(m_state);
227                        luaL_ref( m_state, LUA_REGISTRYINDEX );
228                }
229        }
230
[216]231        if ( load_libs )
232        {
233                stack_guard guard( this );
234                static const luaL_Reg lualibs[] =
235                {
236                        { "string", luaopen_string },
237                        { "table",  luaopen_table },
238                        { "math",   luaopen_math },
239                        { NULL, NULL}
240                };
241                const luaL_Reg *lib = lualibs;
242                for(; lib->func != NULL; lib++)
243                {
[228]244                        lua_pushcfunction( m_state, lib->func );
245                        lua_call(m_state, 0, 1);
246                        lua_setglobal( m_state, lib->name );
[216]247                }
[217]248                register_nova( this );
[216]249        }
250
[365]251        NV_LOG_TRACE( "Lua state created" );
[185]252}
253
[399]254int lua::state::load_string( string_view code, string_view name )
[188]255{
[365]256        NV_LOG_TRACE( "Loading Lua string '", name, "'");
[360]257        return luaL_loadbuffer( m_state, code.data(), code.length(), name.data() );
[188]258}
[185]259
[399]260int lua::state::load_file( string_view filename )
[216]261{
[365]262        NV_LOG_NOTICE( "Loading Lua file '", filename, "'");
[360]263        return luaL_loadfile( m_state, filename.data() );
[216]264}
[212]265
[399]266bool lua::state::do_string( string_view code, string_view name, int rvalues )
[212]267{
[216]268        lua::stack_guard( this );
269        int result = load_string(code,name);
270        if (result)
271        {
[437]272                NV_LOG_WARNING( "Failed to load string ", name, ": ", nlua_tostringview(m_state, -1));
[216]273                return false;
274        }
275        return do_current( name, rvalues ) == 0;
[212]276}
277
[399]278bool lua::state::do_file( string_view filename )
[216]279{
280        lua::stack_guard( this );
281        int result = load_file(filename);
282        if (result)
283        {
[437]284                NV_LOG_WARNING( "Failed to open file ", filename, ": ", nlua_tostringview( m_state, -1 ) );
[216]285                return false;
286        }
287        return do_current( filename ) == 0;
288}
289
[399]290int lua::state::do_current( string_view name, int rvalues )
[216]291{
292        int result = lua_pcall(m_state, 0, rvalues, 0);
293        if (result)
294        {
[437]295                NV_LOG_WARNING( "Failed to run script ", name, ": ", nlua_tostringview( m_state, -1 ) );
[216]296                lua_pop( m_state, 1 );
297        }
298        return result;
299}
300
301int lua::state::get_stack_size()
302{
303        return lua_gettop( m_state );
304}
305
[9]306void lua::state::log_stack()
307{
[206]308        int top = lua_gettop(m_state);
[365]309        NV_LOG_DEBUG( "Stack dump (", top, ")");
[9]310        for ( int i = 0; i < top; ++i )
311        {
[437]312                NV_LOG_DEBUG( "#", i+1, " - ", lua_typename(m_state, lua_type(m_state, i+1) ), " = ", nlua_typecontent(m_state, i+1) );
[9]313        }
314}
315
316lua_State* lua::state::get_raw()
317{
[206]318        return m_state;
[9]319}
320
[399]321lua::ref lua::state::register_object( void* o, string_view lua_name )
[77]322{
[265]323        if ( o == nullptr ) return lua::ref( lua::ref::none );
[77]324        stack_guard guard( this );
[360]325        lua_getglobal( m_state, lua_name.data() );
[206]326        if ( lua_isnil( m_state, -1 ) )
[77]327        {
[403]328                NV_LUA_ABORT( "state::register_object", lua_name, " type not registered!" );
[77]329        }
330        deep_pointer_copy( -1, o );
[265]331        return lua::ref( luaL_ref( m_state, LUA_REGISTRYINDEX ) );
[77]332}
[9]333
[399]334lua::ref lua::state::register_proto( string_view id, string_view storage )
[217]335{
336        stack_guard guard( this );
[360]337        lua_getglobal( m_state, storage.data() );
[217]338        if ( lua_isnil( m_state, -1 ) )
339        {
[403]340                NV_LUA_ABORT( "state::register_proto", "\"", storage, "\" storage not registered!" );
[217]341        }
[360]342        lua_getfield( m_state, -1, id.data() );
[217]343        if ( lua_isnil( m_state, -1 ) )
344        {
[403]345                NV_LUA_ABORT( "state::register_proto", "\"", id, "\" not found in \"", storage, "\"!" );
[217]346        }
[265]347        return lua::ref( luaL_ref( m_state, LUA_REGISTRYINDEX ) );
[217]348}
349
[399]350void lua::state::register_native_object_method( string_view lua_name, string_view name, lfunction f )
[212]351{
352        stack_guard guard( this );
[360]353        lua_getglobal( m_state, lua_name.data() );
[212]354        if ( lua_isnil( m_state, -1 ) )
355        {
[403]356                NV_LUA_ABORT( "state::register_native_object_method", "\"", lua_name, "\" type not registered!" );
[212]357        }
358        lua_pushcfunction( m_state, f );
[360]359        lua_setfield( m_state, -2, name.data() );
[212]360}
361
[265]362void lua::state::unregister_object( ref object_index )
[77]363{
[265]364        if ( !object_index.is_valid() ) return;
[77]365        stack_guard guard( this );
[265]366        lua_rawgeti( m_state, LUA_REGISTRYINDEX, object_index.get() );
[360]367        lua_pushliteral( m_state, "__ptr" );
[206]368        lua_pushboolean( m_state, false );
369        lua_rawset( m_state, -3 );
370        lua_pop( m_state, 1 );
[265]371        luaL_unref( m_state, LUA_REGISTRYINDEX, object_index.get() );
[77]372}
373
[256]374
[77]375void lua::state::deep_pointer_copy( int index, void* obj )
376{
[490]377        index = nlua_absindex( m_state, index );
[206]378        lua_newtable( m_state );
379        lua_pushnil( m_state );
[77]380        bool has_functions = false;
381        bool has_metatable = false;
382
[206]383        while ( lua_next( m_state, index ) != 0 )
[77]384        {
[206]385                if ( lua_isfunction( m_state, -1 ) )
[77]386                        has_functions = true;
[206]387                else if ( lua_istable( m_state, -1 ) )
[77]388                {
389                        deep_pointer_copy( -1, obj );
[206]390                        lua_insert( m_state, -2 );
391                        lua_pop( m_state, 1 );
[77]392                }
[206]393                lua_pushvalue( m_state, -2 );
394                lua_insert( m_state, -2 );
395                lua_settable( m_state, -4 );
[77]396        }
397
[206]398        if ( lua_getmetatable( m_state, -2 ) )
[77]399        {
[206]400                lua_setmetatable( m_state, -2 );
[77]401                has_metatable = true;
402        }
403
404        if ( has_functions || has_metatable )
405        {
[403]406                lua_pushliteral( m_state, "__ptr" );
[206]407                lua_pushlightuserdata( m_state, obj );
408                lua_rawset( m_state, -3 );
[77]409        }
410}
[163]411
[399]412void nv::lua::state::store_metadata( ref object_index, string_view metaname, void* pointer )
[163]413{
[265]414        if ( !object_index.is_valid() ) return;
415        lua_rawgeti( m_state, LUA_REGISTRYINDEX, object_index.get() );
[437]416        nlua_pushstringview( m_state, metaname );
[206]417        lua_pushlightuserdata( m_state, pointer );
418        lua_rawset( m_state, -3 );
419        lua_pop( m_state, 1 );
420}
[188]421
[399]422void nv::lua::state::register_enum( string_view name, int value )
[215]423{
[262]424        lua_pushinteger( m_state, value );
[360]425        lua_setglobal( m_state, name.data() );
[215]426}
427
[511]428void nv::lua::state::register_enum( const type_entry* type )
429{
430        NV_ASSERT_ALWAYS( type, "type not found!" );
431        NV_ASSERT_ALWAYS( !type->enum_list.empty(), "type not enum!" );
432        type_database* db = type->type_db;
433        for ( auto e : type->enum_list )
434        {
435                lua_pushinteger( m_state, e.value );
436                lua_setglobal( m_state, db->resolve_name( e.name ).data() );
437        }
438}
439
[503]440void nv::lua::state::register_rtti_type( thash64 tid, lua_rtti_push_function p, lua_rtti_read_function r )
441{
442        m_lua_types->insert( tid, p, r );
443}
444
[399]445nv::lua::ref nv::lua::state::register_handle_component_impl( string_view id, bool empty )
[341]446{
447        int args = empty ? 1 : 2;
448        NV_LUA_STACK_ASSERT( m_state, -args );
449
450        if ( lua_isnil( m_state, -1 ) || (!empty && lua_isnil( m_state, -2 )) )
451        {
452                lua_pop( m_state, args );
453                return ref();
454        }
455        if (empty)
456                lua_createtable( m_state, 0, 0 );
457        else
458                nlua_deepcopy( m_state, -2 );
[437]459        nlua_pushstringview( m_state, id );
[341]460        lua_pushvalue( m_state, -2 );
461        lua_rawset( m_state, -4 );
462        lua_replace( m_state, -2 );
463        ref result = lua::ref( luaL_ref( m_state, LUA_REGISTRYINDEX ) );
464        if (!empty) lua_pop( m_state, 1 );
465        return result;
466}
467
[399]468void nv::lua::state::unregister_handle_component_impl( string_view id )
[341]469{
470        NV_LUA_STACK_ASSERT( m_state, -1 );
471
472        if ( lua_isnil( m_state, -1 ) )
473        {
474                lua_pop( m_state, 1 );
475                return;
476        }
[437]477        nlua_pushstringview( m_state, id );
[341]478        lua_pushnil( m_state );
479        lua_rawset( m_state, -3 );
480        lua_pop( m_state, 1 );
481}
482
[399]483void nv::lua::state::register_singleton( string_view name, void* o )
[341]484{
485        if ( o == nullptr ) return;
486        stack_guard guard( this );
[360]487        lua_getglobal( m_state, name.data() );
[341]488        if ( lua_isnil( m_state, -1 ) )
489        {
[403]490                NV_LUA_ABORT( "state::register_singleton", "\"", name, "\" type not registered!" );
[341]491        }
492        deep_pointer_copy( -1, o );
[360]493        lua_setglobal( m_state, name.data() );
[341]494}
495
[503]496nv::lua::state::~state()
497{
498        delete m_lua_types;
499        m_lua_types = nullptr;
500}
501
502template < typename T >
503void nlua_rtti_signed_push( nv::lua::state* state, const type_entry*, void* object )
504{
505        T* value = reinterpret_cast<T*>( object );
506        lua_pushinteger( state->get_raw(), lua_Integer( *value ) );
507}
508
509template < typename T >
510void nlua_rtti_unsigned_push( nv::lua::state* state, const type_entry*, void* object )
511{
512        T* value = reinterpret_cast<T*>( object );
513        lua_pushinteger( state->get_raw(), lua_Unsigned( *value ) );
514}
515
516template < typename T >
517void nlua_rtti_floating_push( nv::lua::state* state, const type_entry*, void* object )
518{
519        T* value = reinterpret_cast< T* >( object );
520        lua_pushnumber( state->get_raw(), lua_Number( *value ) );
521}
522
523static void nlua_rtti_boolean_push( nv::lua::state* state, const type_entry*, void* object )
524{
525        bool* value = reinterpret_cast<bool*>( object );
526        lua_pushboolean( state->get_raw(), *value );
527}
528
529template < typename T >
530bool nlua_rtti_signed_read( nv::lua::state* state, const type_entry*, void* object, int index )
531{
532        T* value = reinterpret_cast<T*>( object );
533        if ( lua_type( state->get_raw(), index ) == LUA_TNUMBER )
534        {
535                *value = T( lua_tointeger( state->get_raw(), index ) );
536                return true;
537        }
538        return false;
539}
540
541template < typename T >
542bool nlua_rtti_unsigned_read( nv::lua::state* state, const type_entry*, void* object, int index )
543{
544        T* value = reinterpret_cast<T*>( object );
545        if ( lua_type( state->get_raw(), index ) == LUA_TNUMBER )
546        {
547                *value = T( lua_tointeger( state->get_raw(), index ) );
548                return true;
549        }
550        return false;
551}
552
553template < typename T >
554bool nlua_rtti_floating_read( nv::lua::state* state, const type_entry*, void* object, int index )
555{
556        T* value = reinterpret_cast<T*>( object );
557        if ( lua_type( state->get_raw(), index ) == LUA_TNUMBER )
558        {
559                *value = T( lua_tonumber( state->get_raw(), index ) );
560                return true;
561        }
562        return false;
563}
564
565static bool nlua_rtti_boolean_read( nv::lua::state* state, const type_entry*, void* object, int index )
566{
567        bool* value = reinterpret_cast<bool*>( object );
568        if ( lua_type( state->get_raw(), index ) == LUA_TBOOLEAN )
569        {
[534]570                *value = lua_toboolean( state->get_raw(), index ) != 0;
[503]571                return true;
572        }
573        return false;
574}
575
[540]576template < typename T >
577bool nlua_rtti_string_read( nv::lua::state* state, const type_entry*, void* object, int index )
578{
579        T* value = reinterpret_cast<T*>( object );
580        if ( lua_type( state->get_raw(), index ) == LUA_TSTRING )
581        {
582                *value = T( nlua_tostringview( state->get_raw(), index ) );
583                return true;
584        }
585        return false;
586}
[503]587
[540]588
[503]589void nv::lua::type_data::insert( thash64 tid, lua_rtti_push_function p, lua_rtti_read_function r )
590{
591        m_type_read.assign( tid, r );
592        m_type_push.assign( tid, p );
593}
594
595void nv::lua::type_data::register_standard_types()
596{
597        insert<bool>( nlua_rtti_boolean_push, nlua_rtti_boolean_read );
598        insert<nv::sint8> ( nlua_rtti_signed_push<nv::sint8>,    nlua_rtti_signed_read<nv::sint8> );
599        insert<nv::sint16>( nlua_rtti_signed_push<nv::sint16>,   nlua_rtti_signed_read<nv::sint16> );
600        insert<nv::sint32>( nlua_rtti_signed_push<nv::sint32>,   nlua_rtti_signed_read<nv::sint32> );
601        insert<nv::uint8> ( nlua_rtti_unsigned_push<nv::uint8>,  nlua_rtti_unsigned_read<nv::uint8> );
602        insert<nv::uint16>( nlua_rtti_unsigned_push<nv::uint16>, nlua_rtti_unsigned_read<nv::uint16> );
603        insert<nv::uint32>( nlua_rtti_unsigned_push<nv::uint32>, nlua_rtti_unsigned_read<nv::uint32> );
604        insert<nv::f32>   ( nlua_rtti_floating_push<nv::f32>,    nlua_rtti_floating_read<nv::f32> );
605        insert<nv::f64>   ( nlua_rtti_floating_push<nv::f64>,    nlua_rtti_floating_read<nv::f64> );
[540]606        insert<nv::shash32>  ( nullptr, nlua_rtti_string_read<nv::shash32> );
607        insert<nv::shash64>  ( nullptr, nlua_rtti_string_read<nv::shash64> );
608        insert<nv::string32> ( nullptr, nlua_rtti_string_read<nv::string32> );
609        insert<nv::string64> ( nullptr, nlua_rtti_string_read<nv::string64> );
610        insert<nv::string128>( nullptr, nlua_rtti_string_read<nv::string128> );
611        //      insert<nv::sint64>( nlua_rtti_floating_push<nv::sint64>, nlua_rtti_floating_read<nv::sint64> );
[503]612//      insert<nv::uint64>( nlua_rtti_floating_push<nv::uint64>, nlua_rtti_floating_read<nv::uint64> );
613}
[538]614
Note: See TracBrowser for help on using the repository browser.