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

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