-
Notifications
You must be signed in to change notification settings - Fork 32
/
test.cpp
executable file
·93 lines (75 loc) · 1.72 KB
/
test.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#include <string>
#include <stdio.h>
#include <string.h>
extern "C" {
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
}
// c --> 调用lua --> add_exp --> 调用c
class ACTOR
{
public:
int id;
int exp;
std::string lua_str;
};
struct USE_LUA_ENV
{
ACTOR * actor_ptr;
};
// lua function
USE_LUA_ENV g_use_lua_env;
int init_lua_env();
int lua_env_set(ACTOR * actor);
int lua_env_unset();
int addexp(lua_State* L);
int exec_buff(ACTOR * actor)
{
lua_State* L = luaL_newstate();
luaL_openlibs(L);
// 将指定的函数注册为Lua的全局函数变量,其中第一个字符串参数为Lua代码
// 在调用C函数时使用的全局函数名,第二个参数为实际C函数的指针。
lua_register(L, "addexp", addexp);
lua_env_set(actor);
// 在注册完所有的C函数之后,即可在Lua的代码块中使用这些已经注册的C函数了。
if (luaL_dostring(L, actor->lua_str.c_str()))
{
printf("Failed to invoke.\n");
}
lua_env_unset();
lua_close(L);
printf("actor exec lua buff end \n");
return 0;
}
int main()
{
ACTOR * actor = new ACTOR();
actor->lua_str = "addexp(100)";
actor->exp = 5;
actor->id = 10000;
exec_buff(actor);
return 0;
}
int init_lua_env()
{
memset(&g_use_lua_env, 0, sizeof(g_use_lua_env));
return 0;
}
int lua_env_set(ACTOR * actor)
{
g_use_lua_env.actor_ptr = actor;
}
int lua_env_unset()
{
g_use_lua_env.actor_ptr = 0;
}
int addexp(lua_State* L)
{
int exp = luaL_checknumber(L,1);
ACTOR * actor = g_use_lua_env.actor_ptr;
if (actor == NULL) {return -1;}
actor->exp += exp;
printf("id %d, add exp %d, cur exp %d\n", actor->id, exp, actor->exp);
return 0;
}