面试题答案
一键面试- 引入Lua头文件:在C代码中引入Lua头文件。
#include <lua.h>
#include <lualib.h>
#include <lauxlib.h>
- 加载Lua脚本:
lua_State *L = luaL_newstate();
if (!L) {
// 处理内存分配失败
return -1;
}
luaL_openlibs(L);
if (luaL_dofile(L, "your_script.lua")) {
// 处理加载脚本失败
const char *errmsg = lua_tostring(L, -1);
printf("Error loading Lua script: %s\n", errmsg);
lua_close(L);
return -1;
}
- 调用Lua函数:
// 找到并压入add函数到栈
lua_getglobal(L, "add");
// 压入参数
lua_pushnumber(L, 3);
lua_pushnumber(L, 5);
// 调用函数,2个参数,1个返回值
if (lua_pcall(L, 2, 1, 0)) {
// 处理调用失败
const char *errmsg = lua_tostring(L, -1);
printf("Error calling Lua function: %s\n", errmsg);
lua_close(L);
return -1;
}
// 获取返回值
double result = lua_tonumber(L, -1);
printf("The result of add(3, 5) is: %f\n", result);
// 清理栈
lua_pop(L, 1);
lua_close(L);
完整代码示例:
#include <lua.h>
#include <lualib.h>
#include <lauxlib.h>
#include <stdio.h>
int main() {
lua_State *L = luaL_newstate();
if (!L) {
return -1;
}
luaL_openlibs(L);
if (luaL_dofile(L, "your_script.lua")) {
const char *errmsg = lua_tostring(L, -1);
printf("Error loading Lua script: %s\n", errmsg);
lua_close(L);
return -1;
}
lua_getglobal(L, "add");
lua_pushnumber(L, 3);
lua_pushnumber(L, 5);
if (lua_pcall(L, 2, 1, 0)) {
const char *errmsg = lua_tostring(L, -1);
printf("Error calling Lua function: %s\n", errmsg);
lua_close(L);
return -1;
}
double result = lua_tonumber(L, -1);
printf("The result of add(3, 5) is: %f\n", result);
lua_pop(L, 1);
lua_close(L);
return 0;
}
上述代码实现了在C语言中加载Lua脚本,并调用其中的 add
函数获取两个数之和。注意,需要将 "your_script.lua"
替换为实际的Lua脚本文件名。