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

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