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

Last change on this file since 256 was 256, checked in by epyon, 11 years ago
  • various minor fixes
File size: 11.9 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#include "nv/root.hh"
14#include "nv/types.hh"
15
16using namespace nv;
17
18// stack_guard
19
20lua::stack_guard::stack_guard( lua::state* aL )
21        : L(aL), m_level( lua_gettop(aL->m_state) )
22{
23
24}
25
26lua::stack_guard::stack_guard( lua::state& aL )
27        : L(&aL), m_level( lua_gettop(aL.m_state) )
28{
29
30}
31
32lua::stack_guard::~stack_guard()
33{
34        lua_settop( L->m_state, m_level );
35}
36
37// state_wrapper
38
39void nv::lua::state_wrapper::push_global_table()
40{
41        lua_pushglobaltable( m_state );
42}
43
44void nv::lua::state_wrapper::pop_global_table()
45{
46        lua_replace( m_state, -2 );
47}
48
49void lua::state_wrapper::call_get()
50{
51        lua_gettable( m_state, -2 );
52}
53
54void lua::state_wrapper::call_get_raw()
55{
56        lua_rawget( m_state, -2 );
57}
58
59void lua::state_wrapper::register_native_function( lfunction f, const char* name )
60{
61        if ( m_global ) push_global_table();
62        lua_pushcfunction( m_state, f );
63        lua_setfield( m_state, -2, name );
64        if ( m_global ) pop_global_table();
65}
66
67lua::state_wrapper::~state_wrapper()
68{
69        if (m_owner)
70        {
71                lua_close( m_state );
72        }
73}
74
75bool nv::lua::state_wrapper::is_defined( const path& p, bool global )
76{
77        if ( !p.resolve( m_state, global ) )
78        {
79                return false;
80        }
81        bool result = !lua_isnil( m_state, -1 );
82        lua_pop( m_state, 1 );
83        return result;
84}
85
86bool nv::lua::state_wrapper::push_function( const path& p, bool global )
87{
88        if ( !p.resolve( m_state, global ) )
89        {
90                NV_LOG( LOG_ERROR, "Lua error : not a valid path - " + p.to_string() );
91                return false;
92        }
93
94        if ( !lua_isfunction( m_state, -1 ) )
95        {
96                lua_pop( m_state, 1 );
97                NV_LOG( LOG_ERROR, "Lua error : not a valid function - " + p.to_string() );
98                return false;
99        }
100        return true;
101}
102
103int nv::lua::state_wrapper::call_function( int nargs, int nresults )
104{
105        int status = lua_pcall( m_state, nargs, nresults, 0 );
106        if ( status != 0 )
107        {
108                std::string error = lua_tostring( m_state, -1 );
109                lua_pop( m_state, 1 );
110                NV_LOG( LOG_ERROR, "Lua error : " << error )
111        }
112        return status;
113}
114
115// table_guard
116
117lua::table_guard::table_guard( lua::state* lstate, const path& p, bool global )
118        : state_wrapper( lstate->get_raw(), false ), m_level(0)
119{
120        m_global = false;
121        m_level  = lua_gettop( m_state );
122        if ( !p.resolve( m_state, global ) )
123        {
124                // TODO : error handling
125        }
126}
127
128lua::table_guard::table_guard( const table_guard& parent, const path& p )
129        : state_wrapper( parent.m_state, false ), m_level(0)
130{
131        m_global = false;
132        m_level  = lua_gettop( m_state );
133        if ( !p.resolve( m_state, false ) )
134        {
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
197bool lua::table_guard::get_boolean( const string& element, bool defval /*= "" */ )
198{
199        lua_getfield( m_state, -1, element.c_str() );
200        bool result = lua_type( m_state, -1 ) == LUA_TBOOLEAN ? lua_toboolean( m_state, -1 ) != 0 : defval;
201        lua_pop( m_state, 1 );
202        return result;
203}
204
205// state
206
207lua::state::state( lua_State* state ) : state_wrapper( state, false ), m_type_database( nullptr )
208{
209
210}
211
212lua::state::state( bool load_libs /*= false*/ ) : state_wrapper( nullptr, true ), m_type_database( nullptr )
213{
214        load_lua_library();
215        m_owner = true;
216        m_state = luaL_newstate( );
217
218        lua_pushcfunction(m_state, luaopen_base);
219        lua_pushliteral(m_state, LUA_TABLIBNAME);
220        lua_call(m_state, 1, 0);
221
222        if ( load_libs )
223        {
224                m_type_database = new type_database();
225                stack_guard guard( this );
226                static const luaL_Reg lualibs[] =
227                {
228                        { "string", luaopen_string },
229                        { "table",  luaopen_table },
230                        { "math",   luaopen_math },
231                        { NULL, NULL}
232                };
233                const luaL_Reg *lib = lualibs;
234                for(; lib->func != NULL; lib++)
235                {
236                        lua_pushcfunction( m_state, lib->func );
237                        lua_call(m_state, 0, 1);
238                        lua_setglobal( m_state, lib->name );
239                }
240                register_nova( this );
241        }
242
243        NV_LOG( nv::LOG_TRACE, "Lua state created" );
244}
245
246int lua::state::load_string( const std::string& code, const std::string& name )
247{
248        NV_LOG( nv::LOG_TRACE, "Loading Lua string '" << name << "'");
249        return luaL_loadbuffer( m_state, code.c_str(), code.length(), name.c_str() );
250}
251
252int lua::state::load_stream( std::istream& stream, const std::string& name )
253{
254        NV_LOG( nv::LOG_NOTICE, "Loading Lua stream '" << name << "'");
255        return load_string( std::string(
256                (std::istreambuf_iterator<char>(stream)),
257                std::istreambuf_iterator<char>()), name );
258}
259
260int lua::state::load_file( const std::string& filename )
261{
262        NV_LOG( nv::LOG_NOTICE, "Loading Lua file '" << filename << "'");
263        return luaL_loadfile( m_state, filename.c_str() );
264}
265
266bool lua::state::do_string( const std::string& code, const std::string& name, int rvalues )
267{
268        lua::stack_guard( this );
269        int result = load_string(code,name);
270        if (result)
271        {
272                NV_LOG( nv::LOG_WARNING, "Failed to load string " << name << ": " << lua_tostring(m_state, -1));
273                return false;
274        }
275        return do_current( name, rvalues ) == 0;
276}
277
278bool lua::state::do_stream( std::istream& stream, const std::string& name )
279{
280        lua::stack_guard( this );
281        int result = load_stream(stream,name);
282        if (result)
283        {
284                NV_LOG( nv::LOG_WARNING, "Failed to open stream " << name << ": " << lua_tostring(m_state, -1));
285                return false;
286        }
287        return do_current( name ) == 0;
288}
289
290bool lua::state::do_file( const std::string& filename )
291{
292        lua::stack_guard( this );
293        int result = load_file(filename);
294        if (result)
295        {
296                NV_LOG( nv::LOG_WARNING, "Failed to open file " << filename << ": " << lua_tostring(m_state, -1));
297                return false;
298        }
299        return do_current( filename ) == 0;
300}
301
302int lua::state::do_current( const std::string& name, int rvalues )
303{
304        int result = lua_pcall(m_state, 0, rvalues, 0);
305        if (result)
306        {
307                NV_LOG( nv::LOG_WARNING, "Failed to run script " << name << ": " << lua_tostring(m_state, -1));
308                lua_pop( m_state, 1 );
309        }
310        return result;
311}
312
313int lua::state::get_stack_size()
314{
315        return lua_gettop( m_state );
316}
317
318void lua::state::log_stack()
319{
320        int top = lua_gettop(m_state);
321        NV_LOG( LOG_DEBUG, "Stack dump (" << top << ")");
322        for ( int i = 0; i < top; ++i )
323        {
324                NV_LOG( LOG_DEBUG, "#" << i+1 << " - " << lua_typename(m_state, lua_type(m_state, i+1) ) << " = " << nlua_typecontent(m_state, i+1) );
325        }
326}
327
328lua_State* lua::state::get_raw()
329{
330        return m_state;
331}
332
333lua::reference lua::state::register_object( object * o, const char* lua_name )
334{
335        if ( o == nullptr ) return ref_none;
336        stack_guard guard( this );
337        lua_getglobal( m_state, lua_name );
338        if ( lua_isnil( m_state, -1 ) )
339        {
340                NV_THROW( runtime_error, std::string( lua_name ) + " type not registered!" );
341        }
342        deep_pointer_copy( -1, o );
343        return luaL_ref( m_state, LUA_REGISTRYINDEX );
344}
345
346lua::reference lua::state::register_proto( object * o, const char* storage )
347{
348        stack_guard guard( this );
349        lua_getglobal( m_state, storage );
350        if ( lua_isnil( m_state, -1 ) )
351        {
352                NV_THROW( runtime_error, std::string( storage ) + " storage not registered!" );
353        }
354        lua_getfield( m_state, -1, o->get_id().c_str() );
355        if ( lua_isnil( m_state, -1 ) )
356        {
357                NV_THROW( runtime_error, std::string( o->get_id() ) + " not found in " + std::string( storage ) + " storage!" );
358        }
359        return luaL_ref( m_state, LUA_REGISTRYINDEX );
360}
361
362lua::reference lua::state::register_object( object * o )
363{
364        if ( o == nullptr || m_type_database == nullptr ) return ref_none;
365        type_entry* t = m_type_database->get_type(typeid(*o));
366        if ( t == nullptr ) return ref_none;
367        return register_object( o, t->name.c_str() );
368}
369
370void lua::state::register_native_object_method( const char* lua_name, const char* name, lfunction f )
371{
372        stack_guard guard( this );
373        lua_getglobal( m_state, lua_name );
374        if ( lua_isnil( m_state, -1 ) )
375        {
376                NV_THROW( runtime_error, std::string( lua_name ) + " type not registered!" );
377        }
378        lua_pushcfunction( m_state, f );
379        lua_setfield( m_state, -2, name );
380}
381
382void lua::state::unregister_object( object * o )
383{
384        if (!o) return;
385        unregister_object( o->get_lua_index() );
386}
387
388void lua::state::unregister_object( int index )
389{
390        stack_guard guard( this );
391        lua_rawgeti( m_state, LUA_REGISTRYINDEX, index );
392        lua_pushstring( m_state, "__ptr" );
393        lua_pushboolean( m_state, false );
394        lua_rawset( m_state, -3 );
395        lua_pop( m_state, 1 );
396        luaL_unref( m_state, LUA_REGISTRYINDEX, index );
397}
398
399
400void lua::state::deep_pointer_copy( int index, void* obj )
401{
402        index = lua_absindex( m_state, index );
403        lua_newtable( m_state );
404        lua_pushnil( m_state );
405        bool has_functions = false;
406        bool has_metatable = false;
407
408        while ( lua_next( m_state, index ) != 0 )
409        {
410                if ( lua_isfunction( m_state, -1 ) )
411                        has_functions = true;
412                else if ( lua_istable( m_state, -1 ) )
413                {
414                        deep_pointer_copy( -1, obj );
415                        lua_insert( m_state, -2 );
416                        lua_pop( m_state, 1 );
417                }
418                lua_pushvalue( m_state, -2 );
419                lua_insert( m_state, -2 );
420                lua_settable( m_state, -4 );
421        }
422
423        if ( lua_getmetatable( m_state, -2 ) )
424        {
425                lua_setmetatable( m_state, -2 );
426                has_metatable = true;
427        }
428
429        if ( has_functions || has_metatable )
430        {
431                lua_pushstring( m_state, "__ptr" );
432                lua_pushlightuserdata( m_state, obj );
433                lua_rawset( m_state, -3 );
434        }
435}
436
437void lua::state::register_enum_values( const std::string& name, const std::string& prefix /*= std::string() */ )
438{
439        type_entry* et = m_type_database->get_type( name );
440
441        for ( const auto& entry : et->enum_list )
442        {
443                lua_pushinteger( m_state, entry.value );
444                if ( prefix.empty() )
445                {
446                        lua_setglobal( m_state, entry.name.c_str() );
447                }
448                else
449                {
450                        lua_setglobal( m_state, ( prefix + entry.name ).c_str() );
451                }
452        }
453}
454
455void nv::lua::state::store_metadata( object* o, const std::string& metaname, void* pointer )
456{
457        if (!o) return;
458        stack_guard guard( this );
459        lua_rawgeti( m_state, LUA_REGISTRYINDEX, o->get_lua_index() );
460        lua_pushstring( m_state, metaname.c_str() );
461        lua_pushlightuserdata( m_state, pointer );
462        lua_rawset( m_state, -3 );
463        lua_pop( m_state, 1 );
464}
465
466nv::lua::state::~state()
467{
468        if (m_type_database != nullptr )
469        {
470                delete m_type_database;
471        }
472}
473
Note: See TracBrowser for help on using the repository browser.