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

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