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

Last change on this file since 296 was 296, checked in by epyon, 11 years ago
  • lua::table_guard is_* utility functions
  • minor tweaks
File size: 12.3 KB
Line 
1// Copyright (C) 2012-2013 ChaosForge / Kornel Kisielewicz
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/logging.hh"
12#include "nv/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 ) )
121        {
122                // TODO : error handling
123        }
124}
125
126lua::table_guard::table_guard( const table_guard& parent, const path& p )
127        : state_wrapper( parent.m_state, false ), m_level(0)
128{
129        m_global = false;
130        m_level  = lua_gettop( m_state );
131        if ( !p.resolve( m_state, false ) )
132        {
133                // TODO : error handling
134        }
135}
136
137lua::table_guard::~table_guard()
138{
139        lua_settop( m_state, m_level );
140}
141
142size_t lua::table_guard::get_size()
143{
144        return lua_rawlen( m_state, -1 );
145}
146
147bool lua::table_guard::has_field( const string& element )
148{
149        lua_getfield( m_state, -1, element.c_str() );
150        bool result = !( lua_isnil( m_state, -1 ) );
151        lua_pop( m_state, 1 );
152        return result;
153}
154
155string lua::table_guard::get_string( const string& element, const string& defval /*= "" */ )
156{
157        lua_getfield( m_state, -1, element.c_str() );
158        string result( ( lua_type( m_state, -1 ) == LUA_TSTRING ) ? lua_tostring( m_state, -1 ) : defval );
159        lua_pop( m_state, 1 );
160        return result;
161}
162
163char lua::table_guard::get_char( const string& element, char defval /*= "" */ )
164{
165        lua_getfield( m_state, -1, element.c_str() );
166        char result = ( lua_type( m_state, -1 ) == LUA_TSTRING && lua_rawlen( m_state, -1 ) > 0 ) ? lua_tostring( m_state, -1 )[0] : defval;
167        lua_pop( m_state, 1 );
168        return result;
169}
170
171int lua::table_guard::get_integer( const string& element, int defval /*= "" */ )
172{
173        lua_getfield( m_state, -1, element.c_str() );
174        lua_Integer result = lua_type( m_state, -1 ) == LUA_TNUMBER ? lua_tointeger( m_state, -1 ) : defval;
175        lua_pop( m_state, 1 );
176        return static_cast< int >( result );
177}
178
179unsigned lua::table_guard::get_unsigned( const string& element, unsigned defval /*= "" */ )
180{
181        lua_getfield( m_state, -1, element.c_str() );
182        unsigned result = lua_type( m_state, -1 ) == LUA_TNUMBER ? lua_tounsigned( m_state, -1 ) : defval;
183        lua_pop( m_state, 1 );
184        return result;
185}
186
187double lua::table_guard::get_double( const string& element, double defval /*= "" */ )
188{
189        lua_getfield( m_state, -1, element.c_str() );
190        double result = lua_type( m_state, -1 ) == LUA_TNUMBER ? lua_tonumber( m_state, -1 ) : defval;
191        lua_pop( m_state, 1 );
192        return result;
193}
194
195
196float nv::lua::table_guard::get_float( const std::string& element, float defval /*= 0.0 */ )
197{
198        lua_getfield( m_state, -1, element.c_str() );
199        float result = lua_type( m_state, -1 ) == LUA_TNUMBER ? (float)lua_tonumber( m_state, -1 ) : defval;
200        lua_pop( m_state, 1 );
201        return result;
202}
203
204bool lua::table_guard::get_boolean( const string& element, bool defval /*= "" */ )
205{
206        lua_getfield( m_state, -1, element.c_str() );
207        bool result = lua_type( m_state, -1 ) == LUA_TBOOLEAN ? lua_toboolean( m_state, -1 ) != 0 : defval;
208        lua_pop( m_state, 1 );
209        return result;
210}
211
212bool nv::lua::table_guard::is_table( const std::string& element )
213{
214        lua_getfield( m_state, -1, element.c_str() );
215        bool result = lua_type( m_state, -1 ) == LUA_TTABLE;
216        lua_pop( m_state, 1 );
217        return result;
218}
219
220bool nv::lua::table_guard::is_number( const std::string& element )
221{
222        lua_getfield( m_state, -1, element.c_str() );
223        bool result = lua_type( m_state, -1 ) == LUA_TNUMBER;
224        lua_pop( m_state, 1 );
225        return result;
226}
227
228bool nv::lua::table_guard::is_boolean( const std::string& element )
229{
230        lua_getfield( m_state, -1, element.c_str() );
231        bool result = lua_type( m_state, -1 ) == LUA_TBOOLEAN;
232        lua_pop( m_state, 1 );
233        return result;
234}
235
236bool nv::lua::table_guard::is_string( const std::string& element )
237{
238        lua_getfield( m_state, -1, element.c_str() );
239        bool result = lua_type( m_state, -1 ) == LUA_TSTRING;
240        lua_pop( m_state, 1 );
241        return result;
242}
243
244
245// state
246
247lua::state::state( lua_State* state ) : state_wrapper( state, false )
248{
249
250}
251
252lua::state::state( bool load_libs /*= false*/ ) : state_wrapper( nullptr, true )
253{
254        load_lua_library();
255        m_owner = true;
256        m_state = luaL_newstate( );
257
258        lua_pushcfunction(m_state, luaopen_base);
259        lua_pushliteral(m_state, LUA_TABLIBNAME);
260        lua_call(m_state, 1, 0);
261
262        if ( load_libs )
263        {
264                stack_guard guard( this );
265                static const luaL_Reg lualibs[] =
266                {
267                        { "string", luaopen_string },
268                        { "table",  luaopen_table },
269                        { "math",   luaopen_math },
270                        { NULL, NULL}
271                };
272                const luaL_Reg *lib = lualibs;
273                for(; lib->func != NULL; lib++)
274                {
275                        lua_pushcfunction( m_state, lib->func );
276                        lua_call(m_state, 0, 1);
277                        lua_setglobal( m_state, lib->name );
278                }
279                register_nova( this );
280        }
281
282        NV_LOG( nv::LOG_TRACE, "Lua state created" );
283}
284
285int lua::state::load_string( const std::string& code, const std::string& name )
286{
287        NV_LOG( nv::LOG_TRACE, "Loading Lua string '" << name << "'");
288        return luaL_loadbuffer( m_state, code.c_str(), code.length(), name.c_str() );
289}
290
291int lua::state::load_stream( std::istream& stream, const std::string& name )
292{
293        NV_LOG( nv::LOG_NOTICE, "Loading Lua stream '" << name << "'");
294        return load_string( std::string(
295                (std::istreambuf_iterator<char>(stream)),
296                std::istreambuf_iterator<char>()), name );
297}
298
299int lua::state::load_file( const std::string& filename )
300{
301        NV_LOG( nv::LOG_NOTICE, "Loading Lua file '" << filename << "'");
302        return luaL_loadfile( m_state, filename.c_str() );
303}
304
305bool lua::state::do_string( const std::string& code, const std::string& name, int rvalues )
306{
307        lua::stack_guard( this );
308        int result = load_string(code,name);
309        if (result)
310        {
311                NV_LOG( nv::LOG_WARNING, "Failed to load string " << name << ": " << lua_tostring(m_state, -1));
312                return false;
313        }
314        return do_current( name, rvalues ) == 0;
315}
316
317bool lua::state::do_stream( std::istream& stream, const std::string& name )
318{
319        lua::stack_guard( this );
320        int result = load_stream(stream,name);
321        if (result)
322        {
323                NV_LOG( nv::LOG_WARNING, "Failed to open stream " << name << ": " << lua_tostring(m_state, -1));
324                return false;
325        }
326        return do_current( name ) == 0;
327}
328
329bool lua::state::do_file( const std::string& filename )
330{
331        lua::stack_guard( this );
332        int result = load_file(filename);
333        if (result)
334        {
335                NV_LOG( nv::LOG_WARNING, "Failed to open file " << filename << ": " << lua_tostring(m_state, -1));
336                return false;
337        }
338        return do_current( filename ) == 0;
339}
340
341int lua::state::do_current( const std::string& name, int rvalues )
342{
343        int result = lua_pcall(m_state, 0, rvalues, 0);
344        if (result)
345        {
346                NV_LOG( nv::LOG_WARNING, "Failed to run script " << name << ": " << lua_tostring(m_state, -1));
347                lua_pop( m_state, 1 );
348        }
349        return result;
350}
351
352int lua::state::get_stack_size()
353{
354        return lua_gettop( m_state );
355}
356
357void lua::state::log_stack()
358{
359        int top = lua_gettop(m_state);
360        NV_LOG( LOG_DEBUG, "Stack dump (" << top << ")");
361        for ( int i = 0; i < top; ++i )
362        {
363                NV_LOG( LOG_DEBUG, "#" << i+1 << " - " << lua_typename(m_state, lua_type(m_state, i+1) ) << " = " << nlua_typecontent(m_state, i+1) );
364        }
365}
366
367lua_State* lua::state::get_raw()
368{
369        return m_state;
370}
371
372lua::ref lua::state::register_object( void* o, const char* lua_name )
373{
374        if ( o == nullptr ) return lua::ref( lua::ref::none );
375        stack_guard guard( this );
376        lua_getglobal( m_state, lua_name );
377        if ( lua_isnil( m_state, -1 ) )
378        {
379                NV_THROW( runtime_error, std::string( lua_name ) + " type not registered!" );
380        }
381        deep_pointer_copy( -1, o );
382        return lua::ref( luaL_ref( m_state, LUA_REGISTRYINDEX ) );
383}
384
385lua::ref lua::state::register_proto( const char* id, const char* storage )
386{
387        stack_guard guard( this );
388        lua_getglobal( m_state, storage );
389        if ( lua_isnil( m_state, -1 ) )
390        {
391                NV_THROW( runtime_error, std::string( storage ) + " storage not registered!" );
392        }
393        lua_getfield( m_state, -1, id );
394        if ( lua_isnil( m_state, -1 ) )
395        {
396                NV_THROW( runtime_error, std::string( id ) + " not found in " + std::string( storage ) + " storage!" );
397        }
398        return lua::ref( luaL_ref( m_state, LUA_REGISTRYINDEX ) );
399}
400
401void lua::state::register_native_object_method( const char* lua_name, const char* name, lfunction f )
402{
403        stack_guard guard( this );
404        lua_getglobal( m_state, lua_name );
405        if ( lua_isnil( m_state, -1 ) )
406        {
407                NV_THROW( runtime_error, std::string( lua_name ) + " type not registered!" );
408        }
409        lua_pushcfunction( m_state, f );
410        lua_setfield( m_state, -2, name );
411}
412
413void lua::state::unregister_object( ref object_index )
414{
415        if ( !object_index.is_valid() ) return;
416        stack_guard guard( this );
417        lua_rawgeti( m_state, LUA_REGISTRYINDEX, object_index.get() );
418        lua_pushstring( m_state, "__ptr" );
419        lua_pushboolean( m_state, false );
420        lua_rawset( m_state, -3 );
421        lua_pop( m_state, 1 );
422        luaL_unref( m_state, LUA_REGISTRYINDEX, object_index.get() );
423}
424
425
426void lua::state::deep_pointer_copy( int index, void* obj )
427{
428        index = lua_absindex( m_state, index );
429        lua_newtable( m_state );
430        lua_pushnil( m_state );
431        bool has_functions = false;
432        bool has_metatable = false;
433
434        while ( lua_next( m_state, index ) != 0 )
435        {
436                if ( lua_isfunction( m_state, -1 ) )
437                        has_functions = true;
438                else if ( lua_istable( m_state, -1 ) )
439                {
440                        deep_pointer_copy( -1, obj );
441                        lua_insert( m_state, -2 );
442                        lua_pop( m_state, 1 );
443                }
444                lua_pushvalue( m_state, -2 );
445                lua_insert( m_state, -2 );
446                lua_settable( m_state, -4 );
447        }
448
449        if ( lua_getmetatable( m_state, -2 ) )
450        {
451                lua_setmetatable( m_state, -2 );
452                has_metatable = true;
453        }
454
455        if ( has_functions || has_metatable )
456        {
457                lua_pushstring( m_state, "__ptr" );
458                lua_pushlightuserdata( m_state, obj );
459                lua_rawset( m_state, -3 );
460        }
461}
462
463void nv::lua::state::store_metadata( ref object_index, const std::string& metaname, void* pointer )
464{
465        if ( !object_index.is_valid() ) return;
466        lua_rawgeti( m_state, LUA_REGISTRYINDEX, object_index.get() );
467        lua_pushstring( m_state, metaname.c_str() );
468        lua_pushlightuserdata( m_state, pointer );
469        lua_rawset( m_state, -3 );
470        lua_pop( m_state, 1 );
471}
472
473void nv::lua::state::register_enum( const char* name, int value )
474{
475        lua_pushinteger( m_state, value );
476        lua_setglobal( m_state, name );
477}
478
Note: See TracBrowser for help on using the repository browser.