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

Last change on this file since 341 was 341, checked in by epyon, 11 years ago
  • lua_state - lua component support
  • lua_state - call function from lua::ref
  • lua_state - minor enhancements
File size: 14.6 KB
Line 
1// Copyright (C) 2012-2014 ChaosForge Ltd
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
9#include "nv/lua/lua_raw.hh"
10#include "nv/lua/lua_nova.hh"
11#include "nv/core/logging.hh"
12#include "nv/core/string.hh"
13
14using namespace nv;
15
16// stack_guard
17
18lua::stack_guard::stack_guard( lua::state* aL )
19        : L(aL), m_level( lua_gettop(aL->m_state) )
20{
21
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()
31{
32        lua_settop( L->m_state, m_level );
33}
34
35// stack_assert
36nv::lua::stack_assert::stack_assert( lua::state* aL, int expected )
37        : L(aL->get_raw()), m_expected( lua_gettop(aL->get_raw() ) + expected )
38{
39
40}
41
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), m_expected( lua_gettop(aL) + expected )
50{
51
52}
53
54lua::stack_assert::~stack_assert()
55{
56        NV_ASSERT( lua_gettop(L) == m_expected, "Lua stack corruption detected!" );
57}
58
59
60// state_wrapper
61
62void nv::lua::state_wrapper::push_global_table()
63{
64        lua_pushglobaltable( m_state );
65}
66
67void nv::lua::state_wrapper::pop_global_table()
68{
69        lua_replace( m_state, -2 );
70}
71
72void lua::state_wrapper::call_get()
73{
74        lua_gettable( m_state, -2 );
75}
76
77void lua::state_wrapper::call_get_raw()
78{
79        lua_rawget( m_state, -2 );
80}
81
82void lua::state_wrapper::register_native_function( lfunction f, const char* name )
83{
84        if ( m_global ) push_global_table();
85        lua_pushcfunction( m_state, f );
86        lua_setfield( m_state, -2, name );
87        if ( m_global ) pop_global_table();
88}
89
90lua::state_wrapper::~state_wrapper()
91{
92        if (m_owner)
93        {
94                lua_close( m_state );
95        }
96}
97
98bool nv::lua::state_wrapper::is_defined( const path& p, bool global )
99{
100        if ( !p.resolve( m_state, global ) )
101        {
102                return false;
103        }
104        bool result = !lua_isnil( m_state, -1 );
105        lua_pop( m_state, 1 );
106        return result;
107}
108
109bool nv::lua::state_wrapper::push_function( const path& p, bool global )
110{
111        if ( !p.resolve( m_state, global ) )
112        {
113                NV_LOG( LOG_ERROR, "Lua error : not a valid path - " + p.to_string() );
114                return false;
115        }
116
117        if ( !lua_isfunction( m_state, -1 ) )
118        {
119                lua_pop( m_state, 1 );
120                NV_LOG( LOG_ERROR, "Lua error : not a valid function - " + p.to_string() );
121                return false;
122        }
123        return true;
124}
125
126int nv::lua::state_wrapper::call_function( int nargs, int nresults )
127{
128        int status = lua_pcall( m_state, nargs, nresults, 0 );
129        if ( status != 0 )
130        {
131                std::string error = lua_tostring( m_state, -1 );
132                lua_pop( m_state, 1 );
133                NV_LOG( LOG_ERROR, "Lua error : " << error )
134        }
135        return status;
136}
137
138// table_guard
139
140lua::table_guard::table_guard( lua::state* lstate, const path& p, bool global )
141        : state_wrapper( lstate->get_raw(), false ), m_level(0)
142{
143        m_global = false;
144        m_level  = lua_gettop( m_state );
145        if ( !p.resolve( m_state, global ) || lua_type(m_state, -1) != LUA_TTABLE )
146        {
147                NV_LOG( LOG_ERROR, "Could not resolve table!" );
148                // TODO : error handling
149        }
150}
151
152lua::table_guard::table_guard( const table_guard& parent, const path& p )
153        : state_wrapper( parent.m_state, false ), m_level(0)
154{
155        m_global = false;
156        m_level  = lua_gettop( m_state );
157        if ( !p.resolve( m_state, false ) || lua_type(m_state, -1) != LUA_TTABLE )
158        {
159                NV_LOG( LOG_ERROR, "Could not resolve table!" );
160                // TODO : error handling
161        }
162}
163
164lua::table_guard::~table_guard()
165{
166        lua_settop( m_state, m_level );
167}
168
169size_t lua::table_guard::get_size()
170{
171        return lua_rawlen( m_state, -1 );
172}
173
174bool lua::table_guard::has_field( const string& element )
175{
176        lua_getfield( m_state, -1, element.c_str() );
177        bool result = !( lua_isnil( m_state, -1 ) );
178        lua_pop( m_state, 1 );
179        return result;
180}
181
182string lua::table_guard::get_string( const string& element, const string& defval /*= "" */ )
183{
184        lua_getfield( m_state, -1, element.c_str() );
185        string result( ( lua_type( m_state, -1 ) == LUA_TSTRING ) ? lua_tostring( m_state, -1 ) : defval );
186        lua_pop( m_state, 1 );
187        return result;
188}
189
190char lua::table_guard::get_char( const string& element, char defval /*= "" */ )
191{
192        lua_getfield( m_state, -1, element.c_str() );
193        char result = ( lua_type( m_state, -1 ) == LUA_TSTRING && lua_rawlen( m_state, -1 ) > 0 ) ? lua_tostring( m_state, -1 )[0] : defval;
194        lua_pop( m_state, 1 );
195        return result;
196}
197
198int lua::table_guard::get_integer( const string& element, int defval /*= "" */ )
199{
200        lua_getfield( m_state, -1, element.c_str() );
201        lua_Integer result = lua_type( m_state, -1 ) == LUA_TNUMBER ? lua_tointeger( m_state, -1 ) : defval;
202        lua_pop( m_state, 1 );
203        return static_cast< int >( result );
204}
205
206unsigned lua::table_guard::get_unsigned( const string& element, unsigned defval /*= "" */ )
207{
208        lua_getfield( m_state, -1, element.c_str() );
209        unsigned result = lua_type( m_state, -1 ) == LUA_TNUMBER ? lua_tounsigned( m_state, -1 ) : defval;
210        lua_pop( m_state, 1 );
211        return result;
212}
213
214double lua::table_guard::get_double( const string& element, double defval /*= "" */ )
215{
216        lua_getfield( m_state, -1, element.c_str() );
217        double result = lua_type( m_state, -1 ) == LUA_TNUMBER ? lua_tonumber( m_state, -1 ) : defval;
218        lua_pop( m_state, 1 );
219        return result;
220}
221
222
223float nv::lua::table_guard::get_float( const std::string& element, float defval /*= 0.0 */ )
224{
225        lua_getfield( m_state, -1, element.c_str() );
226        float result = lua_type( m_state, -1 ) == LUA_TNUMBER ? (float)lua_tonumber( m_state, -1 ) : defval;
227        lua_pop( m_state, 1 );
228        return result;
229}
230
231bool lua::table_guard::get_boolean( const string& element, bool defval /*= "" */ )
232{
233        lua_getfield( m_state, -1, element.c_str() );
234        bool result = lua_type( m_state, -1 ) == LUA_TBOOLEAN ? lua_toboolean( m_state, -1 ) != 0 : defval;
235        lua_pop( m_state, 1 );
236        return result;
237}
238
239bool nv::lua::table_guard::is_table( const std::string& element )
240{
241        lua_getfield( m_state, -1, element.c_str() );
242        bool result = lua_type( m_state, -1 ) == LUA_TTABLE;
243        lua_pop( m_state, 1 );
244        return result;
245}
246
247bool nv::lua::table_guard::is_number( const std::string& element )
248{
249        lua_getfield( m_state, -1, element.c_str() );
250        bool result = lua_type( m_state, -1 ) == LUA_TNUMBER;
251        lua_pop( m_state, 1 );
252        return result;
253}
254
255bool nv::lua::table_guard::is_boolean( const std::string& element )
256{
257        lua_getfield( m_state, -1, element.c_str() );
258        bool result = lua_type( m_state, -1 ) == LUA_TBOOLEAN;
259        lua_pop( m_state, 1 );
260        return result;
261}
262
263bool nv::lua::table_guard::is_string( const std::string& element )
264{
265        lua_getfield( m_state, -1, element.c_str() );
266        bool result = lua_type( m_state, -1 ) == LUA_TSTRING;
267        lua_pop( m_state, 1 );
268        return result;
269}
270
271
272// state
273
274lua::state::state( lua_State* state ) : state_wrapper( state, false )
275{
276
277}
278
279lua::state::state( bool load_libs /*= false*/ ) : state_wrapper( nullptr, true )
280{
281        load_lua_library();
282        m_owner = true;
283        m_state = luaL_newstate( );
284
285        lua_pushcfunction(m_state, luaopen_base);
286        lua_pushliteral(m_state, LUA_TABLIBNAME);
287        lua_call(m_state, 1, 0);
288
289        {
290                // Preregister 8 references for Handle registry
291                lua_newtable(m_state);
292                NV_ASSERT( luaL_ref( m_state, LUA_REGISTRYINDEX ) == 1, "First reference not 1!" );
293                for ( uint32 i = 1; i < 8; ++i )
294                {
295                        lua_newtable(m_state);
296                        luaL_ref( m_state, LUA_REGISTRYINDEX );
297                }
298        }
299
300        if ( load_libs )
301        {
302                stack_guard guard( this );
303                static const luaL_Reg lualibs[] =
304                {
305                        { "string", luaopen_string },
306                        { "table",  luaopen_table },
307                        { "math",   luaopen_math },
308                        { NULL, NULL}
309                };
310                const luaL_Reg *lib = lualibs;
311                for(; lib->func != NULL; lib++)
312                {
313                        lua_pushcfunction( m_state, lib->func );
314                        lua_call(m_state, 0, 1);
315                        lua_setglobal( m_state, lib->name );
316                }
317                register_nova( this );
318        }
319
320        NV_LOG( nv::LOG_TRACE, "Lua state created" );
321}
322
323int lua::state::load_string( const std::string& code, const std::string& name )
324{
325        NV_LOG( nv::LOG_TRACE, "Loading Lua string '" << name << "'");
326        return luaL_loadbuffer( m_state, code.c_str(), code.length(), name.c_str() );
327}
328
329int lua::state::load_stream( std::istream& stream, const std::string& name )
330{
331        NV_LOG( nv::LOG_NOTICE, "Loading Lua stream '" << name << "'");
332        return load_string( std::string(
333                (std::istreambuf_iterator<char>(stream)),
334                std::istreambuf_iterator<char>()), name );
335}
336
337int lua::state::load_file( const std::string& filename )
338{
339        NV_LOG( nv::LOG_NOTICE, "Loading Lua file '" << filename << "'");
340        return luaL_loadfile( m_state, filename.c_str() );
341}
342
343bool lua::state::do_string( const std::string& code, const std::string& name, int rvalues )
344{
345        lua::stack_guard( this );
346        int result = load_string(code,name);
347        if (result)
348        {
349                NV_LOG( nv::LOG_WARNING, "Failed to load string " << name << ": " << lua_tostring(m_state, -1));
350                return false;
351        }
352        return do_current( name, rvalues ) == 0;
353}
354
355bool lua::state::do_stream( std::istream& stream, const std::string& name )
356{
357        lua::stack_guard( this );
358        int result = load_stream(stream,name);
359        if (result)
360        {
361                NV_LOG( nv::LOG_WARNING, "Failed to open stream " << name << ": " << lua_tostring(m_state, -1));
362                return false;
363        }
364        return do_current( name ) == 0;
365}
366
367bool lua::state::do_file( const std::string& filename )
368{
369        lua::stack_guard( this );
370        int result = load_file(filename);
371        if (result)
372        {
373                NV_LOG( nv::LOG_WARNING, "Failed to open file " << filename << ": " << lua_tostring(m_state, -1));
374                return false;
375        }
376        return do_current( filename ) == 0;
377}
378
379int lua::state::do_current( const std::string& name, int rvalues )
380{
381        int result = lua_pcall(m_state, 0, rvalues, 0);
382        if (result)
383        {
384                NV_LOG( nv::LOG_WARNING, "Failed to run script " << name << ": " << lua_tostring(m_state, -1));
385                lua_pop( m_state, 1 );
386        }
387        return result;
388}
389
390int lua::state::get_stack_size()
391{
392        return lua_gettop( m_state );
393}
394
395void lua::state::log_stack()
396{
397        int top = lua_gettop(m_state);
398        NV_LOG( LOG_DEBUG, "Stack dump (" << top << ")");
399        for ( int i = 0; i < top; ++i )
400        {
401                NV_LOG( LOG_DEBUG, "#" << i+1 << " - " << lua_typename(m_state, lua_type(m_state, i+1) ) << " = " << nlua_typecontent(m_state, i+1) );
402        }
403}
404
405lua_State* lua::state::get_raw()
406{
407        return m_state;
408}
409
410lua::ref lua::state::register_object( void* o, const char* lua_name )
411{
412        if ( o == nullptr ) return lua::ref( lua::ref::none );
413        stack_guard guard( this );
414        lua_getglobal( m_state, lua_name );
415        if ( lua_isnil( m_state, -1 ) )
416        {
417                NV_THROW( runtime_error, std::string( lua_name ) + " type not registered!" );
418        }
419        deep_pointer_copy( -1, o );
420        return lua::ref( luaL_ref( m_state, LUA_REGISTRYINDEX ) );
421}
422
423lua::ref lua::state::register_proto( const char* id, const char* storage )
424{
425        stack_guard guard( this );
426        lua_getglobal( m_state, storage );
427        if ( lua_isnil( m_state, -1 ) )
428        {
429                NV_THROW( runtime_error, std::string( storage ) + " storage not registered!" );
430        }
431        lua_getfield( m_state, -1, id );
432        if ( lua_isnil( m_state, -1 ) )
433        {
434                NV_THROW( runtime_error, std::string( id ) + " not found in " + std::string( storage ) + " storage!" );
435        }
436        return lua::ref( luaL_ref( m_state, LUA_REGISTRYINDEX ) );
437}
438
439void lua::state::register_native_object_method( const char* lua_name, const char* name, lfunction f )
440{
441        stack_guard guard( this );
442        lua_getglobal( m_state, lua_name );
443        if ( lua_isnil( m_state, -1 ) )
444        {
445                NV_THROW( runtime_error, std::string( lua_name ) + " type not registered!" );
446        }
447        lua_pushcfunction( m_state, f );
448        lua_setfield( m_state, -2, name );
449}
450
451void lua::state::unregister_object( ref object_index )
452{
453        if ( !object_index.is_valid() ) return;
454        stack_guard guard( this );
455        lua_rawgeti( m_state, LUA_REGISTRYINDEX, object_index.get() );
456        lua_pushstring( m_state, "__ptr" );
457        lua_pushboolean( m_state, false );
458        lua_rawset( m_state, -3 );
459        lua_pop( m_state, 1 );
460        luaL_unref( m_state, LUA_REGISTRYINDEX, object_index.get() );
461}
462
463
464void lua::state::deep_pointer_copy( int index, void* obj )
465{
466        index = lua_absindex( m_state, index );
467        lua_newtable( m_state );
468        lua_pushnil( m_state );
469        bool has_functions = false;
470        bool has_metatable = false;
471
472        while ( lua_next( m_state, index ) != 0 )
473        {
474                if ( lua_isfunction( m_state, -1 ) )
475                        has_functions = true;
476                else if ( lua_istable( m_state, -1 ) )
477                {
478                        deep_pointer_copy( -1, obj );
479                        lua_insert( m_state, -2 );
480                        lua_pop( m_state, 1 );
481                }
482                lua_pushvalue( m_state, -2 );
483                lua_insert( m_state, -2 );
484                lua_settable( m_state, -4 );
485        }
486
487        if ( lua_getmetatable( m_state, -2 ) )
488        {
489                lua_setmetatable( m_state, -2 );
490                has_metatable = true;
491        }
492
493        if ( has_functions || has_metatable )
494        {
495                lua_pushstring( m_state, "__ptr" );
496                lua_pushlightuserdata( m_state, obj );
497                lua_rawset( m_state, -3 );
498        }
499}
500
501void nv::lua::state::store_metadata( ref object_index, const std::string& metaname, void* pointer )
502{
503        if ( !object_index.is_valid() ) return;
504        lua_rawgeti( m_state, LUA_REGISTRYINDEX, object_index.get() );
505        lua_pushstring( m_state, metaname.c_str() );
506        lua_pushlightuserdata( m_state, pointer );
507        lua_rawset( m_state, -3 );
508        lua_pop( m_state, 1 );
509}
510
511void nv::lua::state::register_enum( const char* name, int value )
512{
513        lua_pushinteger( m_state, value );
514        lua_setglobal( m_state, name );
515}
516
517nv::lua::ref nv::lua::state::register_handle_component_impl( const std::string& id, bool empty )
518{
519        int args = empty ? 1 : 2;
520        NV_LUA_STACK_ASSERT( m_state, -args );
521
522        if ( lua_isnil( m_state, -1 ) || (!empty && lua_isnil( m_state, -2 )) )
523        {
524                lua_pop( m_state, args );
525                return ref();
526        }
527        if (empty)
528                lua_createtable( m_state, 0, 0 );
529        else
530                nlua_deepcopy( m_state, -2 );
531        lua_pushstring( m_state, id.c_str() );
532        lua_pushvalue( m_state, -2 );
533        lua_rawset( m_state, -4 );
534        lua_replace( m_state, -2 );
535        ref result = lua::ref( luaL_ref( m_state, LUA_REGISTRYINDEX ) );
536        if (!empty) lua_pop( m_state, 1 );
537        return result;
538}
539
540void nv::lua::state::unregister_handle_component_impl( const std::string& id )
541{
542        NV_LUA_STACK_ASSERT( m_state, -1 );
543
544        if ( lua_isnil( m_state, -1 ) )
545        {
546                lua_pop( m_state, 1 );
547                return;
548        }
549        lua_pushstring( m_state, id.c_str() );
550        lua_pushnil( m_state );
551        lua_rawset( m_state, -3 );
552        lua_pop( m_state, 1 );
553}
554
555void nv::lua::state::register_singleton( const char* name, void* o )
556{
557        if ( o == nullptr ) return;
558        stack_guard guard( this );
559        lua_getglobal( m_state, name );
560        if ( lua_isnil( m_state, -1 ) )
561        {
562                NV_THROW( runtime_error, std::string( name ) + " type not registered!" );
563        }
564        deep_pointer_copy( -1, o );
565        lua_setglobal( m_state, name );
566}
567
Note: See TracBrowser for help on using the repository browser.