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

Last change on this file since 361 was 361, checked in by epyon, 10 years ago
  • more string_ref changes
File size: 15.0 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, string_ref name )
83{
84        if ( m_global ) push_global_table();
85        lua_pushcfunction( m_state, f );
86        lua_setfield( m_state, -2, name.data() );
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                NV_LOG( LOG_ERROR, "Lua error : " << lua_tostring( m_state, -1 ) );
132                lua_pop( m_state, 1 );
133        }
134        return status;
135}
136
137// table_guard
138
139lua::table_guard::table_guard( lua::state* lstate, const path& p, bool global )
140        : state_wrapper( lstate->get_raw(), false ), m_level(0)
141{
142        m_global = false;
143        m_level  = lua_gettop( m_state );
144        if ( !p.resolve( m_state, global ) || lua_type(m_state, -1) != LUA_TTABLE )
145        {
146                NV_LOG( LOG_ERROR, "Could not resolve table!" );
147                // TODO : error handling
148        }
149}
150
151lua::table_guard::table_guard( const table_guard& parent, const path& p )
152        : state_wrapper( parent.m_state, false ), m_level(0)
153{
154        m_global = false;
155        m_level  = lua_gettop( m_state );
156        if ( !p.resolve( m_state, false ) || lua_type(m_state, -1) != LUA_TTABLE )
157        {
158                NV_LOG( LOG_ERROR, "Could not resolve table!" );
159                // TODO : error handling
160        }
161}
162
163lua::table_guard::~table_guard()
164{
165        lua_settop( m_state, m_level );
166}
167
168size_t lua::table_guard::get_size()
169{
170        return lua_rawlen( m_state, -1 );
171}
172
173bool lua::table_guard::has_field( string_ref element )
174{
175        lua_getfield( m_state, -1, element.data() );
176        bool result = !( lua_isnil( m_state, -1 ) );
177        lua_pop( m_state, 1 );
178        return result;
179}
180
181string lua::table_guard::get_std_string( string_ref element, string_ref defval /*= string_ref() */ )
182{
183        lua_getfield( m_state, -1, element.data() );
184        size_t l = 0;
185        const char* str = nullptr;
186        if ( lua_type( m_state, -1 ) == LUA_TSTRING )
187        {
188                str = lua_tolstring( m_state, -1, &l );
189        }
190        else
191        {
192                l = defval.size();
193                str = defval.data();
194        }
195        std::string result( str, l );
196        lua_pop( m_state, 1 );
197        return result;
198}
199
200const_string lua::table_guard::get_string( string_ref element, string_ref defval /*= string_ref() */ )
201{
202        lua_getfield( m_state, -1, element.data() );
203        size_t l = 0;
204        const char* str = nullptr;
205        if ( lua_type( m_state, -1 ) == LUA_TSTRING )
206        {
207                str = lua_tolstring( m_state, -1, &l );
208        }
209        else
210        {
211                l = defval.size();
212                str = defval.data();
213        }
214        const_string result( str, l );
215        lua_pop( m_state, 1 );
216        return result;
217}
218
219char lua::table_guard::get_char( string_ref element, char defval /*= "" */ )
220{
221        lua_getfield( m_state, -1, element.data() );
222        char result = ( lua_type( m_state, -1 ) == LUA_TSTRING && lua_rawlen( m_state, -1 ) > 0 ) ? lua_tostring( m_state, -1 )[0] : defval;
223        lua_pop( m_state, 1 );
224        return result;
225}
226
227int lua::table_guard::get_integer( string_ref element, int defval /*= "" */ )
228{
229        lua_getfield( m_state, -1, element.data() );
230        lua_Integer result = lua_type( m_state, -1 ) == LUA_TNUMBER ? lua_tointeger( m_state, -1 ) : defval;
231        lua_pop( m_state, 1 );
232        return static_cast< int >( result );
233}
234
235unsigned lua::table_guard::get_unsigned( string_ref element, unsigned defval /*= "" */ )
236{
237        lua_getfield( m_state, -1, element.data() );
238        unsigned result = lua_type( m_state, -1 ) == LUA_TNUMBER ? lua_tounsigned( m_state, -1 ) : defval;
239        lua_pop( m_state, 1 );
240        return result;
241}
242
243double lua::table_guard::get_double( string_ref element, double defval /*= "" */ )
244{
245        lua_getfield( m_state, -1, element.data() );
246        double result = lua_type( m_state, -1 ) == LUA_TNUMBER ? lua_tonumber( m_state, -1 ) : defval;
247        lua_pop( m_state, 1 );
248        return result;
249}
250
251
252float nv::lua::table_guard::get_float( string_ref element, float defval /*= 0.0 */ )
253{
254        lua_getfield( m_state, -1, element.data() );
255        float result = lua_type( m_state, -1 ) == LUA_TNUMBER ? (float)lua_tonumber( m_state, -1 ) : defval;
256        lua_pop( m_state, 1 );
257        return result;
258}
259
260bool lua::table_guard::get_boolean( string_ref element, bool defval /*= "" */ )
261{
262        lua_getfield( m_state, -1, element.data() );
263        bool result = lua_type( m_state, -1 ) == LUA_TBOOLEAN ? lua_toboolean( m_state, -1 ) != 0 : defval;
264        lua_pop( m_state, 1 );
265        return result;
266}
267
268bool nv::lua::table_guard::is_table( string_ref element )
269{
270        lua_getfield( m_state, -1, element.data() );
271        bool result = lua_type( m_state, -1 ) == LUA_TTABLE;
272        lua_pop( m_state, 1 );
273        return result;
274}
275
276bool nv::lua::table_guard::is_number( string_ref element )
277{
278        lua_getfield( m_state, -1, element.data() );
279        bool result = lua_type( m_state, -1 ) == LUA_TNUMBER;
280        lua_pop( m_state, 1 );
281        return result;
282}
283
284bool nv::lua::table_guard::is_boolean( string_ref element )
285{
286        lua_getfield( m_state, -1, element.data() );
287        bool result = lua_type( m_state, -1 ) == LUA_TBOOLEAN;
288        lua_pop( m_state, 1 );
289        return result;
290}
291
292bool nv::lua::table_guard::is_string( string_ref element )
293{
294        lua_getfield( m_state, -1, element.data() );
295        bool result = lua_type( m_state, -1 ) == LUA_TSTRING;
296        lua_pop( m_state, 1 );
297        return result;
298}
299
300
301// state
302
303lua::state::state( lua_State* state ) : state_wrapper( state, false )
304{
305
306}
307
308lua::state::state( bool load_libs /*= false*/ ) : state_wrapper( nullptr, true )
309{
310        load_lua_library();
311        m_owner = true;
312        m_state = luaL_newstate( );
313
314        lua_pushcfunction(m_state, luaopen_base);
315        lua_pushliteral(m_state, LUA_TABLIBNAME);
316        lua_call(m_state, 1, 0);
317
318        {
319                // Preregister 8 references for Handle registry
320                lua_newtable(m_state);
321                NV_ASSERT( luaL_ref( m_state, LUA_REGISTRYINDEX ) == 1, "First reference not 1!" );
322                for ( uint32 i = 1; i < 8; ++i )
323                {
324                        lua_newtable(m_state);
325                        luaL_ref( m_state, LUA_REGISTRYINDEX );
326                }
327        }
328
329        if ( load_libs )
330        {
331                stack_guard guard( this );
332                static const luaL_Reg lualibs[] =
333                {
334                        { "string", luaopen_string },
335                        { "table",  luaopen_table },
336                        { "math",   luaopen_math },
337                        { NULL, NULL}
338                };
339                const luaL_Reg *lib = lualibs;
340                for(; lib->func != NULL; lib++)
341                {
342                        lua_pushcfunction( m_state, lib->func );
343                        lua_call(m_state, 0, 1);
344                        lua_setglobal( m_state, lib->name );
345                }
346                register_nova( this );
347        }
348
349        NV_LOG( nv::LOG_TRACE, "Lua state created" );
350}
351
352int lua::state::load_string( string_ref code, string_ref name )
353{
354        NV_LOG( nv::LOG_TRACE, "Loading Lua string '" << name << "'");
355        return luaL_loadbuffer( m_state, code.data(), code.length(), name.data() );
356}
357
358int lua::state::load_stream( std::istream& stream, string_ref name )
359{
360        NV_LOG( nv::LOG_NOTICE, "Loading Lua stream '" << name << "'");
361        return load_string( std::string(
362                (std::istreambuf_iterator<char>(stream)),
363                std::istreambuf_iterator<char>()), name );
364}
365
366int lua::state::load_file( string_ref filename )
367{
368        NV_LOG( nv::LOG_NOTICE, "Loading Lua file '" << filename << "'");
369        return luaL_loadfile( m_state, filename.data() );
370}
371
372bool lua::state::do_string( string_ref code, string_ref name, int rvalues )
373{
374        lua::stack_guard( this );
375        int result = load_string(code,name);
376        if (result)
377        {
378                NV_LOG( nv::LOG_WARNING, "Failed to load string " << name << ": " << lua_tostring(m_state, -1));
379                return false;
380        }
381        return do_current( name, rvalues ) == 0;
382}
383
384bool lua::state::do_stream( std::istream& stream, string_ref name )
385{
386        lua::stack_guard( this );
387        int result = load_stream(stream,name);
388        if (result)
389        {
390                NV_LOG( nv::LOG_WARNING, "Failed to open stream " << name << ": " << lua_tostring(m_state, -1));
391                return false;
392        }
393        return do_current( name ) == 0;
394}
395
396bool lua::state::do_file( string_ref filename )
397{
398        lua::stack_guard( this );
399        int result = load_file(filename);
400        if (result)
401        {
402                NV_LOG( nv::LOG_WARNING, "Failed to open file " << filename << ": " << lua_tostring(m_state, -1));
403                return false;
404        }
405        return do_current( filename ) == 0;
406}
407
408int lua::state::do_current( string_ref name, int rvalues )
409{
410        int result = lua_pcall(m_state, 0, rvalues, 0);
411        if (result)
412        {
413                NV_LOG( nv::LOG_WARNING, "Failed to run script " << name << ": " << lua_tostring(m_state, -1));
414                lua_pop( m_state, 1 );
415        }
416        return result;
417}
418
419int lua::state::get_stack_size()
420{
421        return lua_gettop( m_state );
422}
423
424void lua::state::log_stack()
425{
426        int top = lua_gettop(m_state);
427        NV_LOG( LOG_DEBUG, "Stack dump (" << top << ")");
428        for ( int i = 0; i < top; ++i )
429        {
430                NV_LOG( LOG_DEBUG, "#" << i+1 << " - " << lua_typename(m_state, lua_type(m_state, i+1) ) << " = " << nlua_typecontent(m_state, i+1) );
431        }
432}
433
434lua_State* lua::state::get_raw()
435{
436        return m_state;
437}
438
439lua::ref lua::state::register_object( void* o, string_ref lua_name )
440{
441        if ( o == nullptr ) return lua::ref( lua::ref::none );
442        stack_guard guard( this );
443        lua_getglobal( m_state, lua_name.data() );
444        if ( lua_isnil( m_state, -1 ) )
445        {
446                NV_THROW( runtime_error, lua_name.to_string() + " type not registered!" );
447        }
448        deep_pointer_copy( -1, o );
449        return lua::ref( luaL_ref( m_state, LUA_REGISTRYINDEX ) );
450}
451
452lua::ref lua::state::register_proto( string_ref id, string_ref storage )
453{
454        stack_guard guard( this );
455        lua_getglobal( m_state, storage.data() );
456        if ( lua_isnil( m_state, -1 ) )
457        {
458                NV_THROW( runtime_error, storage.to_string() + " storage not registered!" );
459        }
460        lua_getfield( m_state, -1, id.data() );
461        if ( lua_isnil( m_state, -1 ) )
462        {
463                NV_THROW( runtime_error, id.to_string() + " not found in " + storage.to_string() + " storage!" );
464        }
465        return lua::ref( luaL_ref( m_state, LUA_REGISTRYINDEX ) );
466}
467
468void lua::state::register_native_object_method( string_ref lua_name, string_ref name, lfunction f )
469{
470        stack_guard guard( this );
471        lua_getglobal( m_state, lua_name.data() );
472        if ( lua_isnil( m_state, -1 ) )
473        {
474                NV_THROW( runtime_error, lua_name.to_string() + " type not registered!" );
475        }
476        lua_pushcfunction( m_state, f );
477        lua_setfield( m_state, -2, name.data() );
478}
479
480void lua::state::unregister_object( ref object_index )
481{
482        if ( !object_index.is_valid() ) return;
483        stack_guard guard( this );
484        lua_rawgeti( m_state, LUA_REGISTRYINDEX, object_index.get() );
485        lua_pushliteral( m_state, "__ptr" );
486        lua_pushboolean( m_state, false );
487        lua_rawset( m_state, -3 );
488        lua_pop( m_state, 1 );
489        luaL_unref( m_state, LUA_REGISTRYINDEX, object_index.get() );
490}
491
492
493void lua::state::deep_pointer_copy( int index, void* obj )
494{
495        index = lua_absindex( m_state, index );
496        lua_newtable( m_state );
497        lua_pushnil( m_state );
498        bool has_functions = false;
499        bool has_metatable = false;
500
501        while ( lua_next( m_state, index ) != 0 )
502        {
503                if ( lua_isfunction( m_state, -1 ) )
504                        has_functions = true;
505                else if ( lua_istable( m_state, -1 ) )
506                {
507                        deep_pointer_copy( -1, obj );
508                        lua_insert( m_state, -2 );
509                        lua_pop( m_state, 1 );
510                }
511                lua_pushvalue( m_state, -2 );
512                lua_insert( m_state, -2 );
513                lua_settable( m_state, -4 );
514        }
515
516        if ( lua_getmetatable( m_state, -2 ) )
517        {
518                lua_setmetatable( m_state, -2 );
519                has_metatable = true;
520        }
521
522        if ( has_functions || has_metatable )
523        {
524                lua_pushstring( m_state, "__ptr" );
525                lua_pushlightuserdata( m_state, obj );
526                lua_rawset( m_state, -3 );
527        }
528}
529
530void nv::lua::state::store_metadata( ref object_index, string_ref metaname, void* pointer )
531{
532        if ( !object_index.is_valid() ) return;
533        lua_rawgeti( m_state, LUA_REGISTRYINDEX, object_index.get() );
534        lua_pushlstring( m_state, metaname.data(), metaname.size() );
535        lua_pushlightuserdata( m_state, pointer );
536        lua_rawset( m_state, -3 );
537        lua_pop( m_state, 1 );
538}
539
540void nv::lua::state::register_enum( string_ref name, int value )
541{
542        lua_pushinteger( m_state, value );
543        lua_setglobal( m_state, name.data() );
544}
545
546nv::lua::ref nv::lua::state::register_handle_component_impl( string_ref id, bool empty )
547{
548        int args = empty ? 1 : 2;
549        NV_LUA_STACK_ASSERT( m_state, -args );
550
551        if ( lua_isnil( m_state, -1 ) || (!empty && lua_isnil( m_state, -2 )) )
552        {
553                lua_pop( m_state, args );
554                return ref();
555        }
556        if (empty)
557                lua_createtable( m_state, 0, 0 );
558        else
559                nlua_deepcopy( m_state, -2 );
560        lua_pushlstring( m_state, id.data(), id.size() );
561        lua_pushvalue( m_state, -2 );
562        lua_rawset( m_state, -4 );
563        lua_replace( m_state, -2 );
564        ref result = lua::ref( luaL_ref( m_state, LUA_REGISTRYINDEX ) );
565        if (!empty) lua_pop( m_state, 1 );
566        return result;
567}
568
569void nv::lua::state::unregister_handle_component_impl( string_ref id )
570{
571        NV_LUA_STACK_ASSERT( m_state, -1 );
572
573        if ( lua_isnil( m_state, -1 ) )
574        {
575                lua_pop( m_state, 1 );
576                return;
577        }
578        lua_pushlstring( m_state, id.data(), id.size() );
579        lua_pushnil( m_state );
580        lua_rawset( m_state, -3 );
581        lua_pop( m_state, 1 );
582}
583
584void nv::lua::state::register_singleton( string_ref name, void* o )
585{
586        if ( o == nullptr ) return;
587        stack_guard guard( this );
588        lua_getglobal( m_state, name.data() );
589        if ( lua_isnil( m_state, -1 ) )
590        {
591                NV_THROW( runtime_error, name.to_string() + " type not registered!" );
592        }
593        deep_pointer_copy( -1, o );
594        lua_setglobal( m_state, name.data() );
595}
596
Note: See TracBrowser for help on using the repository browser.