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

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