1 | // Copyright (C) 2012-2015 ChaosForge Ltd
|
---|
2 | // http://chaosforge.org/
|
---|
3 | //
|
---|
4 | // This file is part of Nova libraries.
|
---|
5 | // For conditions of distribution and use, see copying.txt file in root folder.
|
---|
6 |
|
---|
7 | #include "nv/lua/lua_function.hh"
|
---|
8 |
|
---|
9 | #include "nv/core/logging.hh"
|
---|
10 | #include "nv/lua/lua_raw.hh"
|
---|
11 |
|
---|
12 | using namespace nv;
|
---|
13 |
|
---|
14 | #define NV_LUA_ABORT( func, ... ) \
|
---|
15 | NV_LOG_CRITICAL( "lua::" func " : ", __VA_ARGS__ ) \
|
---|
16 | NV_ABORT( "lua::" func " : critical error!" )
|
---|
17 |
|
---|
18 | lua::function_base::function_base( lua_State* a_L, const path& a_path, bool a_global /*= true*/ ) : L(a_L)
|
---|
19 | {
|
---|
20 | if ( !a_path.resolve( L, a_global ) )
|
---|
21 | {
|
---|
22 | lua_pop( L, 1 );
|
---|
23 | NV_LUA_ABORT( "function_base::function_base", "not a valid path - ", a_path.to_string() );
|
---|
24 | }
|
---|
25 |
|
---|
26 | if ( !lua_isfunction( L, -1 ) )
|
---|
27 | {
|
---|
28 | lua_pop( L, 1 );
|
---|
29 | NV_LUA_ABORT( "function_base::function_base", "not a valid function - ", a_path.to_string() );
|
---|
30 | }
|
---|
31 | m_ref = luaL_ref( L, LUA_REGISTRYINDEX );
|
---|
32 | }
|
---|
33 |
|
---|
34 | lua::function_base::function_base( const function_base& func ) : L(func.L)
|
---|
35 | {
|
---|
36 | lua_rawgeti( L, LUA_REGISTRYINDEX, func.m_ref );
|
---|
37 | m_ref = luaL_ref( L, LUA_REGISTRYINDEX );
|
---|
38 | }
|
---|
39 |
|
---|
40 | lua::function_base::~function_base()
|
---|
41 | {
|
---|
42 | luaL_unref( L, LUA_REGISTRYINDEX, m_ref );
|
---|
43 | }
|
---|
44 |
|
---|
45 | lua::function_base& lua::function_base::operator=(const function_base& func)
|
---|
46 | {
|
---|
47 | if ( this != &func )
|
---|
48 | {
|
---|
49 | L = func.L;
|
---|
50 | lua_rawgeti( L, LUA_REGISTRYINDEX, func.m_ref );
|
---|
51 | m_ref = luaL_ref( L, LUA_REGISTRYINDEX );
|
---|
52 | }
|
---|
53 | return *this;
|
---|
54 | }
|
---|
55 |
|
---|
56 | void lua::function_base::retrieve()
|
---|
57 | {
|
---|
58 | lua_rawgeti( L, LUA_REGISTRYINDEX, m_ref );
|
---|
59 | }
|
---|
60 |
|
---|
61 | void lua::function_base::call( int args, int results )
|
---|
62 | {
|
---|
63 | int status = lua_pcall( L, args, results, 0 );
|
---|
64 | if ( status != 0 )
|
---|
65 | {
|
---|
66 | std::string error = lua_tostring( L, -1 );
|
---|
67 | lua_pop( L, 1 );
|
---|
68 | NV_LUA_ABORT( "function_base::call", "call failed - ", error.c_str() );
|
---|
69 | }
|
---|
70 | }
|
---|
71 |
|
---|