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
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}
156
157lua::table_guard::table_guard( const table_guard& parent, const path& p )
158        : state_wrapper( parent.m_state, parent.m_lua_types, false ), m_parent( parent.m_parent ), m_level(0)
159{
160        m_global = false;
161        m_level  = lua_gettop( m_state );
162        if ( !p.resolve( m_state, false ) || lua_type(m_state, -1) != LUA_TTABLE )
163        {
164                NV_LOG_ERROR( "Could not resolve table!" );
165                // TODO : error handling
166        }
167}
168
169lua::table_guard::~table_guard()
170{
171        lua_settop( m_state, m_level );
172}
173
174nv::uint32 lua::table_guard::get_size()
175{
176        return nlua_rawlen( m_state, -1 );
177}
178
179bool lua::table_guard::has_field( string_view element )
180{
181        lua_getfield( m_state, -1, element.data() );
182        bool result = !( lua_isnil( m_state, -1 ) );
183        lua_pop( m_state, 1 );
184        return result;
185}
186
187const nv::lua::temporary_proxy nv::lua::table_guard::operator[]( const string_view& key ) const
188{
189        lua_getfield( m_state, -1, key.data() );
190        return temporary_proxy( m_parent );
191}
192
193const nv::lua::temporary_proxy nv::lua::table_guard::operator[]( sint32 key ) const
194{
195        lua_rawgeti( m_state, -1, key );
196        return temporary_proxy( m_parent );
197}
198
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
217// state
218
219lua::state::state( lua_State* state, type_database* types )
220        : state_wrapper( state, new type_data( types ), false )
221{
222
223}
224
225lua::state::state( bool load_libs /*= false*/, type_database* types )
226        : state_wrapper( nullptr, new type_data( types ), true )
227{
228        load_lua_library();
229        m_owner = true;
230        m_state = luaL_newstate( );
231
232        lua_pushcfunction(m_state, luaopen_base);
233        lua_pushliteral(m_state, "");
234        lua_call(m_state, 1, 0);
235
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
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                {
260                        lua_pushcfunction( m_state, lib->func );
261                        lua_call(m_state, 0, 1);
262                        lua_setglobal( m_state, lib->name );
263                }
264                register_nova( this );
265        }
266
267        NV_LOG_TRACE( "Lua state created" );
268}
269
270int lua::state::load_string( string_view code, string_view name )
271{
272        NV_LOG_TRACE( "Loading Lua string '", name, "'");
273        return luaL_loadbuffer( m_state, code.data(), code.length(), name.data() );
274}
275
276int lua::state::load_file( string_view filename )
277{
278        NV_LOG_NOTICE( "Loading Lua file '", filename, "'");
279        return luaL_loadfile( m_state, filename.data() );
280}
281
282bool lua::state::do_string( string_view code, string_view name, int rvalues )
283{
284        lua::stack_guard( this );
285        int result = load_string(code,name);
286        if (result)
287        {
288                NV_LOG_WARNING( "Failed to load string ", name, ": ", nlua_tostringview(m_state, -1));
289                return false;
290        }
291        return do_current( name, rvalues ) == 0;
292}
293
294bool lua::state::do_file( string_view filename )
295{
296        lua::stack_guard( this );
297        int result = load_file(filename);
298        if (result)
299        {
300                NV_LOG_WARNING( "Failed to open file ", filename, ": ", nlua_tostringview( m_state, -1 ) );
301                return false;
302        }
303        return do_current( filename ) == 0;
304}
305
306int lua::state::do_current( string_view name, int rvalues )
307{
308        int result = lua_pcall(m_state, 0, rvalues, 0);
309        if (result)
310        {
311                NV_LOG_WARNING( "Failed to run script ", name, ": ", nlua_tostringview( m_state, -1 ) );
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
322void lua::state::log_stack()
323{
324        int top = lua_gettop(m_state);
325        NV_LOG_DEBUG( "Stack dump (", top, ")");
326        for ( int i = 0; i < top; ++i )
327        {
328                NV_LOG_DEBUG( "#", i+1, " - ", lua_typename(m_state, lua_type(m_state, i+1) ), " = ", nlua_typecontent(m_state, i+1) );
329        }
330}
331
332lua_State* lua::state::get_raw()
333{
334        return m_state;
335}
336
337lua::ref lua::state::register_object( void* o, string_view lua_name )
338{
339        if ( o == nullptr ) return lua::ref( lua::ref::none );
340        stack_guard guard( this );
341        lua_getglobal( m_state, lua_name.data() );
342        if ( lua_isnil( m_state, -1 ) )
343        {
344                NV_LUA_ABORT( "state::register_object", lua_name, " type not registered!" );
345        }
346        deep_pointer_copy( -1, o );
347        return lua::ref( luaL_ref( m_state, LUA_REGISTRYINDEX ) );
348}
349
350lua::ref lua::state::register_proto( string_view id, string_view storage )
351{
352        stack_guard guard( this );
353        lua_getglobal( m_state, storage.data() );
354        if ( lua_isnil( m_state, -1 ) )
355        {
356                NV_LUA_ABORT( "state::register_proto", "\"", storage, "\" storage not registered!" );
357        }
358        lua_getfield( m_state, -1, id.data() );
359        if ( lua_isnil( m_state, -1 ) )
360        {
361                NV_LUA_ABORT( "state::register_proto", "\"", id, "\" not found in \"", storage, "\"!" );
362        }
363        return lua::ref( luaL_ref( m_state, LUA_REGISTRYINDEX ) );
364}
365
366void lua::state::register_native_object_method( string_view lua_name, string_view name, lfunction f )
367{
368        stack_guard guard( this );
369        lua_getglobal( m_state, lua_name.data() );
370        if ( lua_isnil( m_state, -1 ) )
371        {
372                NV_LUA_ABORT( "state::register_native_object_method", "\"", lua_name, "\" type not registered!" );
373        }
374        lua_pushcfunction( m_state, f );
375        lua_setfield( m_state, -2, name.data() );
376}
377
378void lua::state::unregister_object( ref object_index )
379{
380        if ( !object_index.is_valid() ) return;
381        stack_guard guard( this );
382        lua_rawgeti( m_state, LUA_REGISTRYINDEX, object_index.get() );
383        lua_pushliteral( m_state, "__ptr" );
384        lua_pushboolean( m_state, false );
385        lua_rawset( m_state, -3 );
386        lua_pop( m_state, 1 );
387        luaL_unref( m_state, LUA_REGISTRYINDEX, object_index.get() );
388}
389
390
391void lua::state::deep_pointer_copy( int index, void* obj )
392{
393        index = nlua_absindex( m_state, index );
394        lua_newtable( m_state );
395        lua_pushnil( m_state );
396        bool has_functions = false;
397        bool has_metatable = false;
398
399        while ( lua_next( m_state, index ) != 0 )
400        {
401                if ( lua_isfunction( m_state, -1 ) )
402                        has_functions = true;
403                else if ( lua_istable( m_state, -1 ) )
404                {
405                        deep_pointer_copy( -1, obj );
406                        lua_insert( m_state, -2 );
407                        lua_pop( m_state, 1 );
408                }
409                lua_pushvalue( m_state, -2 );
410                lua_insert( m_state, -2 );
411                lua_settable( m_state, -4 );
412        }
413
414        if ( lua_getmetatable( m_state, -2 ) )
415        {
416                lua_setmetatable( m_state, -2 );
417                has_metatable = true;
418        }
419
420        if ( has_functions || has_metatable )
421        {
422                lua_pushliteral( m_state, "__ptr" );
423                lua_pushlightuserdata( m_state, obj );
424                lua_rawset( m_state, -3 );
425        }
426}
427
428void nv::lua::state::store_metadata( ref object_index, string_view metaname, void* pointer )
429{
430        if ( !object_index.is_valid() ) return;
431        lua_rawgeti( m_state, LUA_REGISTRYINDEX, object_index.get() );
432        nlua_pushstringview( m_state, metaname );
433        lua_pushlightuserdata( m_state, pointer );
434        lua_rawset( m_state, -3 );
435        lua_pop( m_state, 1 );
436}
437
438void nv::lua::state::register_enum( string_view name, int value )
439{
440        lua_pushinteger( m_state, value );
441        lua_setglobal( m_state, name.data() );
442}
443
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
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
461nv::lua::ref nv::lua::state::register_handle_component_impl( string_view id, bool empty )
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 );
475        nlua_pushstringview( m_state, id );
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
484void nv::lua::state::unregister_handle_component_impl( string_view id )
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        }
493        nlua_pushstringview( m_state, id );
494        lua_pushnil( m_state );
495        lua_rawset( m_state, -3 );
496        lua_pop( m_state, 1 );
497}
498
499void nv::lua::state::register_singleton( string_view name, void* o )
500{
501        if ( o == nullptr ) return;
502        stack_guard guard( this );
503        lua_getglobal( m_state, name.data() );
504        if ( lua_isnil( m_state, -1 ) )
505        {
506                NV_LUA_ABORT( "state::register_singleton", "\"", name, "\" type not registered!" );
507        }
508        deep_pointer_copy( -1, o );
509        lua_setglobal( m_state, name.data() );
510}
511
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        {
586                *value = lua_toboolean( state->get_raw(), index ) != 0;
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}
613
Note: See TracBrowser for help on using the repository browser.