写一个lua调用c和c调用lua的程序
时间: 2023-10-09 08:09:12 浏览: 46
以下是一个简单的示例程序,其中Lua调用了C函数,C函数又回调了Lua函数。
C代码:
```c
#include <stdio.h>
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
static int c_hello(lua_State *L) {
printf("Hello from C!\n");
return 0;
}
static int c_call_lua(lua_State *L) {
const char *str = luaL_checkstring(L, 1);
printf("C calling Lua: %s\n", str);
lua_pushinteger(L, 12345);
lua_pushstring(L, "Hello from Lua!");
return 2;
}
static int c_call_lua_callback(lua_State *L) {
const char *str = luaL_checkstring(L, 1);
lua_Integer num = luaL_checkinteger(L, 2);
luaL_checktype(L, 3, LUA_TFUNCTION);
lua_pushvalue(L, 3); // 把回调函数压入栈中
lua_pushstring(L, str);
lua_pushinteger(L, num);
int result = lua_pcall(L, 2, 1, 0); // 调用回调函数
if (result != 0) {
printf("Error calling Lua callback: %s\n", lua_tostring(L, -1));
lua_pop(L, 1);
return 0;
}
const char *ret_str = lua_tostring(L, -1);
printf("C received from Lua callback: %s\n", ret_str);
return 0;
}
int main() {
lua_State *L = luaL_newstate();
luaL_openlibs(L);
lua_pushcfunction(L, c_hello);
lua_setglobal(L, "c_hello");
lua_pushcfunction(L, c_call_lua);
lua_setglobal(L, "c_call_lua");
lua_pushcfunction(L, c_call_lua_callback);
lua_setglobal(L, "c_call_lua_callback");
luaL_dostring(L, "function lua_hello() print('Hello from Lua!') end");
luaL_dostring(L, "c_hello()");
luaL_dostring(L, "print(c_call_lua('Hello from C!'))");
luaL_dostring(L, "c_call_lua_callback('Hello from C callback!', 123, function(str, num) print('Lua callback received:', str, num) return 'Hello from Lua callback!' end)");
lua_close(L);
return 0;
}
```
Lua代码:
```lua
local function lua_callback(str, num)
print("Lua received from C callback:", str, num)
return "Hello from Lua callback!"
end
c_hello()
local num, str = c_call_lua("Hello from Lua!")
print("Lua received from C:", num, str)
c_call_lua_callback("Hello from Lua callback!", 123, lua_callback)
```
在运行该程序时,会输出以下内容:
```
Hello from C!
12345 Hello from Lua!
Lua callback received: Hello from C callback! 123
C received from Lua callback: Hello from Lua callback!
Lua received from C callback: Hello from Lua callback! 123
```