直接看代碼琐谤,代碼中有相關(guān)注釋甩鳄。
c-lua-struct.c
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>
/* 結(jié)構(gòu)體定義 */
typedef struct
{
int x;
int y;
char *str;
}TData;
int call_lua_fun(lua_State *L, int a, int b)
{
/* 初始化結(jié)構(gòu)體 */
TData data;
data.x = a;
data.y = b;
data.str = malloc(10);
memset(data.str, 'c', 9);
data.str[9] = '\0';
/* 獲取Lua腳本中函數(shù)名為“fun”的函數(shù)并壓入棧中 */
lua_getglobal(L, "fun");
/* 創(chuàng)建一個新的table并壓入棧中 */
lua_newtable(L);
/* 第一個操作數(shù)入棧蚤氏,int類型可以用lua_pushinteger或lua_pushnumber */
lua_pushinteger(L, data.x);
/*
* 將值設(shè)置到table中锻弓,Lua腳本中可以用“.a”獲取結(jié)構(gòu)體x成員的值
* 第三個參數(shù)的值可以隨便取辣辫,只要和Lua腳本中保持一致即可
*/
lua_setfield(L, -2, "a");
/* 第二個操作數(shù)入棧 */
lua_pushnumber(L, data.y);
lua_setfield(L, -2, "b");
/* 第三個操作數(shù)入棧,char*用lua_pushstring */
lua_pushstring(L, data.str);
lua_setfield(L, -2, "s");
/*
* 調(diào)用函數(shù)忧便,調(diào)用完成后族吻,會將返回值壓入棧中
* 第二個參數(shù)表示入?yún)€數(shù),第三個參數(shù)表示返回結(jié)果個數(shù)
*/
lua_pcall(L, 1, 1, 0);
/* 獲取棧頂元素(結(jié)果) */
int sum = (int)lua_tonumber(L, -1);
/* 清除堆棧、清除計(jì)算結(jié)果 */
lua_pop(L, 1);
return sum;
}
int main(int argc, char *argv[])
{
/* 新建Lua解釋器 */
lua_State *L = luaL_newstate();
/* 載入Lua基本庫 */
luaL_openlibs(L);
/* 運(yùn)行腳本fun.lua */
luaL_dofile(L, "fun.lua");
printf("%d\n", call_lua_fun(L, 5, 6));
/* 清除Lua */
lua_close(L);
return 0;
}
fun.lua
function fun(x)
print(type(x))
print("s=[" .. x.s .. "]")
return x.a + x.b;
end
編譯命令
gcc c-lua-struct.c -o c-lua-struct -I /usr/local/include/luajit-2.0 -llua-5.1 -L /usr/lib64/
運(yùn)行
./c-lua-struct
輸出結(jié)果
table
s=[ccccccccc]
11