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
Line 
1// Copyright (C) 2012-2015 ChaosForge Ltd
2// http://chaosforge.org/
3//
4// This file is part of Nova libraries.
5// For conditions of distribution and use, see copying.txt file in root folder.
6
7#include "nv/lua/lua_state.hh"
8
9#include "nv/lua/lua_raw.hh"
10#include "nv/lua/lua_nova.hh"
11#include "nv/lua/lua_types.hh"
12#include "nv/core/logging.hh"
13#include "nv/stl/string.hh"
14
15using namespace nv;
16
17// stack_guard
18
19#define NV_LUA_ABORT( func, ... ) \
20        NV_LOG_CRITICAL( "lua::" func " : ", __VA_ARGS__ ) \
21        NV_ABORT( "lua::" func " : critical error!" )
22
23
24lua::stack_guard::stack_guard( lua::state* aL )
25        : L(aL), m_level( lua_gettop(aL->m_state) )
26{
27
28}
29
30lua::stack_guard::stack_guard( lua::state& aL )
31        : L(&aL), m_level( lua_gettop(aL.m_state) )
32{
33
34}
35
36lua::stack_guard::~stack_guard()
37{
38        lua_settop( L->m_state, m_level );
39}
40
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
66// state_wrapper
67
68void nv::lua::state_wrapper::push_global_table()
69{
70        nlua_pushglobaltable( m_state );
71}
72
73void nv::lua::state_wrapper::pop_global_table()
74{
75        lua_replace( m_state, -2 );
76}
77
78void lua::state_wrapper::call_get()
79{
80        lua_gettable( m_state, -2 );
81}
82
83void lua::state_wrapper::call_get_raw()
84{
85        lua_rawget( m_state, -2 );
86}
87
88void lua::state_wrapper::register_native_function( lfunction f, string_view name )
89{
90        if ( m_global ) push_global_table();
91        lua_pushcfunction( m_state, f );
92        lua_setfield( m_state, -2, name.data() );
93        if ( m_global ) pop_global_table();
94}
95
96lua::state_wrapper::~state_wrapper()
97{
98        if (m_owner)
99        {
100                lua_close( m_state );
101        }
102}
103
104bool nv::lua::state_wrapper::is_defined( const path& p, bool global )
105{
106        if ( !p.resolve( m_state, global ) )
107        {
108                return false;
109        }
110        bool result = !lua_isnil( m_state, -1 );
111        lua_pop( m_state, 1 );
112        return result;
113}
114
115bool nv::lua::state_wrapper::push_function( const path& p, bool global )
116{
117        if ( !p.resolve( m_state, global ) )
118        {
119                NV_LOG_ERROR( "Lua error : not a valid path - ", p.to_string() );
120                return false;
121        }
122
123        if ( !lua_isfunction( m_state, -1 ) )
124        {
125                lua_pop( m_state, 1 );
126                NV_LOG_ERROR( "Lua error : not a valid function - ", p.to_string() );
127                return false;
128        }
129        return true;
130}
131
132int nv::lua::state_wrapper::call_function( int nargs, int nresults )
133{
134        int status = lua_pcall( m_state, nargs, nresults, 0 );
135        if ( status != 0 )
136        {
137                NV_LOG_ERROR( "Lua error : ", nlua_tostringview( m_state, -1 ) );
138                lua_pop( m_state, 1 );
139        }
140        return status;
141}
142
143// table_guard
144
145lua::table_guard::table_guard( lua::state* lstate, const path& p, bool global )
146        : state_wrapper( lstate->get_raw(), lstate->m_lua_types, false ), m_parent( lstate ), m_level(0)
147{
148        m_global = false;
149        m_level  = lua_gettop( m_state );
150        if ( !p.resolve( m_state, global ) || lua_type(m_state, -1) != LUA_TTABLE )
151        {
152                NV_LOG_ERROR( "Could not resolve table!" );
153                // TODO : error handling
154        }
155        m_index = -1;
156}
157
158lua::table_guard::table_guard( const table_guard& parent, const path& p )
159        : state_wrapper( parent.m_state, parent.m_lua_types, false ), m_parent( parent.m_parent ), m_level(0)
160{
161        m_global = false;
162        m_level  = lua_gettop( m_state );
163        if ( !p.resolve( m_state, false ) || lua_type(m_state, -1) != LUA_TTABLE )
164        {
165                NV_LOG_ERROR( "Could not resolve table!" );
166                // TODO : error handling
167        }
168        m_index = -1;
169}
170
171lua::table_guard::~table_guard()
172{
173        if ( m_index == -1 )
174                lua_settop( m_state, m_level );
175}
176
177nv::uint32 lua::table_guard::size()
178{
179        return nlua_rawlen( m_state, m_index );
180}
181
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 )
184{
185        m_level = lua_gettop( m_state );
186        m_index = proxy.m_index;
187}
188
189const nv::lua::temporary_proxy nv::lua::table_guard::operator[]( const string_view& key ) const
190{
191        lua_getfield( m_state, m_index, key.data() );
192        return temporary_proxy( m_parent );
193}
194
195const nv::lua::temporary_proxy nv::lua::table_guard::operator[]( sint32 key ) const
196{
197        lua_rawgeti( m_state, m_index, key );
198        return temporary_proxy( m_parent );
199}
200
201// state
202
203lua::state::state( lua_State* state, type_database* types )
204        : state_wrapper( state, new type_data( types ), false )
205{
206
207}
208
209lua::state::state( bool load_libs /*= false*/, type_database* types )
210        : state_wrapper( nullptr, new type_data( types ), true )
211{
212        load_lua_library();
213        m_owner = true;
214        m_state = luaL_newstate( );
215
216        lua_pushcfunction(m_state, luaopen_base);
217        lua_pushliteral(m_state, "");
218        lua_call(m_state, 1, 0);
219
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
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                {
244                        lua_pushcfunction( m_state, lib->func );
245                        lua_call(m_state, 0, 1);
246                        lua_setglobal( m_state, lib->name );
247                }
248                register_nova( this );
249        }
250
251        NV_LOG_TRACE( "Lua state created" );
252}
253
254int lua::state::load_string( string_view code, string_view name )
255{
256        NV_LOG_TRACE( "Loading Lua string '", name, "'");
257        return luaL_loadbuffer( m_state, code.data(), code.length(), name.data() );
258}
259
260int lua::state::load_file( string_view filename )
261{
262        NV_LOG_NOTICE( "Loading Lua file '", filename, "'");
263        return luaL_loadfile( m_state, filename.data() );
264}
265
266bool lua::state::do_string( string_view code, string_view name, int rvalues )
267{
268        lua::stack_guard( this );
269        int result = load_string(code,name);
270        if (result)
271        {
272                NV_LOG_WARNING( "Failed to load string ", name, ": ", nlua_tostringview(m_state, -1));
273                return false;
274        }
275        return do_current( name, rvalues ) == 0;
276}
277
278bool lua::state::do_file( string_view filename )
279{
280        lua::stack_guard( this );
281        int result = load_file(filename);
282        if (result)
283        {
284                NV_LOG_WARNING( "Failed to open file ", filename, ": ", nlua_tostringview( m_state, -1 ) );
285                return false;
286        }
287        return do_current( filename ) == 0;
288}
289
290int lua::state::do_current( string_view name, int rvalues )
291{
292        int result = lua_pcall(m_state, 0, rvalues, 0);
293        if (result)
294        {
295                NV_LOG_WARNING( "Failed to run script ", name, ": ", nlua_tostringview( m_state, -1 ) );
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
306void lua::state::log_stack()
307{
308        int top = lua_gettop(m_state);
309        NV_LOG_DEBUG( "Stack dump (", top, ")");
310        for ( int i = 0; i < top; ++i )
311        {
312                NV_LOG_DEBUG( "#", i+1, " - ", lua_typename(m_state, lua_type(m_state, i+1) ), " = ", nlua_typecontent(m_state, i+1) );
313        }
314}
315
316lua_State* lua::state::get_raw()
317{
318        return m_state;
319}
320
321lua::ref lua::state::register_object( void* o, string_view lua_name )
322{
323        if ( o == nullptr ) return lua::ref( lua::ref::none );
324        stack_guard guard( this );
325        lua_getglobal( m_state, lua_name.data() );
326        if ( lua_isnil( m_state, -1 ) )
327        {
328                NV_LUA_ABORT( "state::register_object", lua_name, " type not registered!" );
329        }
330        deep_pointer_copy( -1, o );
331        return lua::ref( luaL_ref( m_state, LUA_REGISTRYINDEX ) );
332}
333
334lua::ref lua::state::register_proto( string_view id, string_view storage )
335{
336        stack_guard guard( this );
337        lua_getglobal( m_state, storage.data() );
338        if ( lua_isnil( m_state, -1 ) )
339        {
340                NV_LUA_ABORT( "state::register_proto", "\"", storage, "\" storage not registered!" );
341        }
342        lua_getfield( m_state, -1, id.data() );
343        if ( lua_isnil( m_state, -1 ) )
344        {
345                NV_LUA_ABORT( "state::register_proto", "\"", id, "\" not found in \"", storage, "\"!" );
346        }
347        return lua::ref( luaL_ref( m_state, LUA_REGISTRYINDEX ) );
348}
349
350void lua::state::register_native_object_method( string_view lua_name, string_view name, lfunction f )
351{
352        stack_guard guard( this );
353        lua_getglobal( m_state, lua_name.data() );
354        if ( lua_isnil( m_state, -1 ) )
355        {
356                NV_LUA_ABORT( "state::register_native_object_method", "\"", lua_name, "\" type not registered!" );
357        }
358        lua_pushcfunction( m_state, f );
359        lua_setfield( m_state, -2, name.data() );
360}
361
362void lua::state::unregister_object( ref object_index )
363{
364        if ( !object_index.is_valid() ) return;
365        stack_guard guard( this );
366        lua_rawgeti( m_state, LUA_REGISTRYINDEX, object_index.get() );
367        lua_pushliteral( 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, object_index.get() );
372}
373
374
375void lua::state::deep_pointer_copy( int index, void* obj )
376{
377        index = nlua_absindex( m_state, index );
378        lua_newtable( m_state );
379        lua_pushnil( m_state );
380        bool has_functions = false;
381        bool has_metatable = false;
382
383        while ( lua_next( m_state, index ) != 0 )
384        {
385                if ( lua_isfunction( m_state, -1 ) )
386                        has_functions = true;
387                else if ( lua_istable( m_state, -1 ) )
388                {
389                        deep_pointer_copy( -1, obj );
390                        lua_insert( m_state, -2 );
391                        lua_pop( m_state, 1 );
392                }
393                lua_pushvalue( m_state, -2 );
394                lua_insert( m_state, -2 );
395                lua_settable( m_state, -4 );
396        }
397
398        if ( lua_getmetatable( m_state, -2 ) )
399        {
400                lua_setmetatable( m_state, -2 );
401                has_metatable = true;
402        }
403
404        if ( has_functions || has_metatable )
405        {
406                lua_pushliteral( m_state, "__ptr" );
407                lua_pushlightuserdata( m_state, obj );
408                lua_rawset( m_state, -3 );
409        }
410}
411
412void nv::lua::state::store_metadata( ref object_index, string_view metaname, void* pointer )
413{
414        if ( !object_index.is_valid() ) return;
415        lua_rawgeti( m_state, LUA_REGISTRYINDEX, object_index.get() );
416        nlua_pushstringview( m_state, metaname );
417        lua_pushlightuserdata( m_state, pointer );
418        lua_rawset( m_state, -3 );
419        lua_pop( m_state, 1 );
420}
421
422void nv::lua::state::register_enum( string_view name, int value )
423{
424        lua_pushinteger( m_state, value );
425        lua_setglobal( m_state, name.data() );
426}
427
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
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
445nv::lua::ref nv::lua::state::register_handle_component_impl( string_view id, bool empty )
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 );
459        nlua_pushstringview( m_state, id );
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
468void nv::lua::state::unregister_handle_component_impl( string_view id )
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        }
477        nlua_pushstringview( m_state, id );
478        lua_pushnil( m_state );
479        lua_rawset( m_state, -3 );
480        lua_pop( m_state, 1 );
481}
482
483void nv::lua::state::register_singleton( string_view name, void* o )
484{
485        if ( o == nullptr ) return;
486        stack_guard guard( this );
487        lua_getglobal( m_state, name.data() );
488        if ( lua_isnil( m_state, -1 ) )
489        {
490                NV_LUA_ABORT( "state::register_singleton", "\"", name, "\" type not registered!" );
491        }
492        deep_pointer_copy( -1, o );
493        lua_setglobal( m_state, name.data() );
494}
495
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        {
570                *value = lua_toboolean( state->get_raw(), index ) != 0;
571                return true;
572        }
573        return false;
574}
575
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}
587
588
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> );
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> );
612//      insert<nv::uint64>( nlua_rtti_floating_push<nv::uint64>, nlua_rtti_floating_read<nv::uint64> );
613}
614
Note: See TracBrowser for help on using the repository browser.