-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.cpp
More file actions
73 lines (56 loc) · 1.54 KB
/
Copy pathmain.cpp
File metadata and controls
73 lines (56 loc) · 1.54 KB
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
#include <filesystem>
#include <fstream>
extern "C" {
#include "lauxlib.h"
#include "lua.h"
#include "lualib.h"
}
using namespace std;
extern "C" int LuaPrint(lua_State* L) {
const char* s = lua_tostring(L, 1);
printf("%s", s);
return 0;
}
extern "C" int LuaFoo(lua_State* L) {
int n = lua_gettop(L); // argc
lua_Number sum = 0.0;
int i;
for (i = 1; i <= n; i++) {
if (!lua_isnumber(L, i)) {
lua_pushliteral(L, "invalid argument");
lua_error(L);
}
sum += lua_tonumber(L, i);
}
lua_pushnumber(L, n); // first return val
lua_pushnumber(L, sum); // second return val
return 2; // return num
}
int32_t main(int32_t argc, char** argv) {
lua_State* L = luaL_newstate();
luaL_openlibs(L);
lua_register(L, "print", LuaPrint);
lua_register(L, "foo", LuaFoo);
const std::filesystem::path& script_file = std::filesystem::absolute("./test.lua");
std::ofstream ofile(script_file, std::ios::trunc);
ofile << R"str(
-- testlib
print("test test !!!\n")
local n, sum = foo(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
print("n:" .. n .. ", sum:" .. sum .. "\n")
function testluafun(a, b)
return (a .. b)
end
)str";
ofile.close();
int ret = luaL_dofile(L, script_file.string().c_str());
if (ret) printf("load lua script ret:%d, msg:%s\n", ret, lua_tostring(L, -1));
lua_getglobal(L, "testluafun");
lua_pushstring(L, "aaa");
lua_pushstring(L, "bbb");
lua_pcall(L, 2, 1, 0);
std::string lua_ret = lua_tostring(L, -1);
printf("testluafun ret:%s\n", lua_ret.c_str());
lua_close(L);
return 0;
}