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

Last change on this file since 217 was 217, checked in by epyon, 12 years ago
  • lua/nova - almost complete reimplementation of "core" from FPC Valkyrie
  • lua/state - nova loaded by default
  • object - prototype reference caching
File size: 11.8 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                        lib->func( m_state );
237                }
238                register_nova( this );
239        }
240
241        NV_LOG( nv::LOG_TRACE, "Lua state created" );
242}
243
244int lua::state::load_string( const std::string& code, const std::string& name )
245{
246        NV_LOG( nv::LOG_TRACE, "Loading Lua string '" << name << "'");
247        return luaL_loadbuffer( m_state, code.c_str(), code.length(), name.c_str() );
248}
249
250int lua::state::load_stream( std::istream& stream, const std::string& name )
251{
252        NV_LOG( nv::LOG_NOTICE, "Loading Lua stream '" << name << "'");
253        return load_string( std::string(
254                (std::istreambuf_iterator<char>(stream)),
255                std::istreambuf_iterator<char>()), name );
256}
257
258int lua::state::load_file( const std::string& filename )
259{
260        NV_LOG( nv::LOG_NOTICE, "Loading Lua file '" << filename << "'");
261        return luaL_loadfile( m_state, filename.c_str() );
262}
263
264bool lua::state::do_string( const std::string& code, const std::string& name, int rvalues )
265{
266        lua::stack_guard( this );
267        int result = load_string(code,name);
268        if (result)
269        {
270                NV_LOG( nv::LOG_WARNING, "Failed to load string " << name << ": " << lua_tostring(m_state, -1));
271                return false;
272        }
273        return do_current( name, rvalues ) == 0;
274}
275
276bool lua::state::do_stream( std::istream& stream, const std::string& name )
277{
278        lua::stack_guard( this );
279        int result = load_stream(stream,name);
280        if (result)
281        {
282                NV_LOG( nv::LOG_WARNING, "Failed to open stream " << name << ": " << lua_tostring(m_state, -1));
283                return false;
284        }
285        return do_current( name ) == 0;
286}
287
288bool lua::state::do_file( const std::string& filename )
289{
290        lua::stack_guard( this );
291        int result = load_file(filename);
292        if (result)
293        {
294                NV_LOG( nv::LOG_WARNING, "Failed to open file " << filename << ": " << lua_tostring(m_state, -1));
295                return false;
296        }
297        return do_current( filename ) == 0;
298}
299
300int lua::state::do_current( const std::string& name, int rvalues )
301{
302        int result = lua_pcall(m_state, 0, rvalues, 0);
303        if (result)
304        {
305                NV_LOG( nv::LOG_WARNING, "Failed to run script " << name << ": " << lua_tostring(m_state, -1));
306                lua_pop( m_state, 1 );
307        }
308        return result;
309}
310
311int lua::state::get_stack_size()
312{
313        return lua_gettop( m_state );
314}
315
316void lua::state::log_stack()
317{
318        int top = lua_gettop(m_state);
319        NV_LOG( LOG_DEBUG, "Stack dump (" << top << ")");
320        for ( int i = 0; i < top; ++i )
321        {
322                NV_LOG( LOG_DEBUG, "#" << i+1 << " - " << lua_typename(m_state, lua_type(m_state, i+1) ) << " = " << nlua_typecontent(m_state, i+1) );
323        }
324}
325
326lua_State* lua::state::get_raw()
327{
328        return m_state;
329}
330
331lua::reference lua::state::register_object( object * o, const char* lua_name )
332{
333        if ( o == nullptr ) return ref_none;
334        stack_guard guard( this );
335        lua_getglobal( m_state, lua_name );
336        if ( lua_isnil( m_state, -1 ) )
337        {
338                NV_THROW( runtime_error, std::string( lua_name ) + " type not registered!" );
339        }
340        deep_pointer_copy( -1, o );
341        return luaL_ref( m_state, LUA_REGISTRYINDEX );
342}
343
344lua::reference lua::state::register_proto( object * o, const char* storage )
345{
346        stack_guard guard( this );
347        lua_getglobal( m_state, storage );
348        if ( lua_isnil( m_state, -1 ) )
349        {
350                NV_THROW( runtime_error, std::string( storage ) + " storage not registered!" );
351        }
352        lua_getfield( m_state, -1, o->get_id().c_str() );
353        if ( lua_isnil( m_state, -1 ) )
354        {
355                NV_THROW( runtime_error, std::string( o->get_id() ) + " not found in " + std::string( storage ) + " storage!" );
356        }
357        return luaL_ref( m_state, LUA_REGISTRYINDEX );
358}
359
360lua::reference lua::state::register_object( object * o )
361{
362        if ( o == nullptr || m_type_database == nullptr ) return ref_none;
363        type_entry* t = m_type_database->get_type(typeid(*o));
364        if ( t == nullptr ) return ref_none;
365        return register_object( o, t->name.c_str() );
366}
367
368void lua::state::register_native_object_method( const char* lua_name, const char* name, lfunction f )
369{
370        stack_guard guard( this );
371        lua_getglobal( m_state, lua_name );
372        if ( lua_isnil( m_state, -1 ) )
373        {
374                NV_THROW( runtime_error, std::string( lua_name ) + " type not registered!" );
375        }
376        lua_pushcfunction( m_state, f );
377        lua_setfield( m_state, -2, name );
378}
379
380void lua::state::unregister_object( object * o )
381{
382        if (!o) return;
383        stack_guard guard( this );
384        lua_rawgeti( m_state, LUA_REGISTRYINDEX, o->get_lua_index() );
385        lua_pushstring( m_state, "__ptr" );
386        lua_pushboolean( m_state, false );
387        lua_rawset( m_state, -3 );
388        lua_pop( m_state, 1 );
389        luaL_unref( m_state, LUA_REGISTRYINDEX, o->get_lua_index() );
390}
391
392void lua::state::deep_pointer_copy( int index, void* obj )
393{
394        index = lua_absindex( m_state, index );
395        lua_newtable( m_state );
396        lua_pushnil( m_state );
397        bool has_functions = false;
398        bool has_metatable = false;
399
400        while ( lua_next( m_state, index ) != 0 )
401        {
402                if ( lua_isfunction( m_state, -1 ) )
403                        has_functions = true;
404                else if ( lua_istable( m_state, -1 ) )
405                {
406                        deep_pointer_copy( -1, obj );
407                        lua_insert( m_state, -2 );
408                        lua_pop( m_state, 1 );
409                }
410                lua_pushvalue( m_state, -2 );
411                lua_insert( m_state, -2 );
412                lua_settable( m_state, -4 );
413        }
414
415        if ( lua_getmetatable( m_state, -2 ) )
416        {
417                lua_setmetatable( m_state, -2 );
418                has_metatable = true;
419        }
420
421        if ( has_functions || has_metatable )
422        {
423                lua_pushstring( m_state, "__ptr" );
424                lua_pushlightuserdata( m_state, obj );
425                lua_rawset( m_state, -3 );
426        }
427}
428
429void lua::state::register_enum_values( const std::string& name, const std::string& prefix /*= std::string() */ )
430{
431        type_entry* et = m_type_database->get_type( name );
432
433        for ( const auto& entry : et->enum_list )
434        {
435                lua_pushinteger( m_state, entry.value );
436                if ( prefix.empty() )
437                {
438                        lua_setglobal( m_state, entry.name.c_str() );
439                }
440                else
441                {
442                        lua_setglobal( m_state, ( prefix + entry.name ).c_str() );
443                }
444        }
445}
446
447void nv::lua::state::store_metadata( object* o, const std::string& metaname, void* pointer )
448{
449        if (!o) return;
450        stack_guard guard( this );
451        lua_rawgeti( m_state, LUA_REGISTRYINDEX, o->get_lua_index() );
452        lua_pushstring( m_state, metaname.c_str() );
453        lua_pushlightuserdata( m_state, pointer );
454        lua_rawset( m_state, -3 );
455        lua_pop( m_state, 1 );
456}
457
458nv::lua::state::~state()
459{
460        if (m_type_database != nullptr )
461        {
462                delete m_type_database;
463        }
464}
465
Note: See TracBrowser for help on using the repository browser.