您的位置:首页 > 编程语言 > Lua

c和lua进行的一些基础交互和处理,这里留用lua5.1

2017-11-15 20:50 337 查看
#include <iostream>

extern "C" {
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
}

static int my_add(lua_State *L)
{
int a = luaL_checknumber(L, 1);
int b = luaL_checknumber(L, 2);
lua_pushnumber(L, a + b);
return 1;
}

static const struct luaL_Reg mylib[] = {
{"madd", my_add },
{NULL, NULL}
};

int main(int argc, char** argv) {
lua_State *L = luaL_newstate();
luaL_openlibs(L);
//=============================================
//c和lua交互部分
lua_pushcfunction(L, my_add);
lua_setglobal(L, "madd"); // lua中调用时 print(madd(10,20))

luaL_register(L, "mylib", mylib); // lua中调用时 local lib require "mylib" print(lib.madd(10,20))

//============================================
//lua调用c函数
// 参考上面
//============================================
//c调用lua函数
lua_getglobal(L, "math");
//lua_pushstring(L, "min");
lua_getfield(L, -1, "pow");
if (lua_isfunction(L, -1))
{
lua_pushinteger(L, 3);
lua_pushinteger(L, 2);
lua_call(L, 2, 1);
printf("result:%d\n", lua_tointeger(L, -1));
lua_pop(L, 1);
}

//============================================
//c中操作lua的表, 索引和kv操作
lua_newtable(L);
lua_pushstring(L, "key");
lua_pushstring(L, "mm");
//由于上面两次压栈,现在table元素排在栈顶往下数第三的位置
lua_settable(L, -3);    //lua_settable会自己弹出上面压入的key和value

for (int i = 1; i < 10; i++) {
lua_pushinteger(L, i);
//lua_pushstring(L, "gogoxxxx" + i);
lua_pushfstring(L, "gogoxxxx%d", i);
lua_settable(L, -3);
}

lua_setglobal(L, "mk");  //lua_settable会自己弹出上面压入的key和value

//============================================
//c中遍历lua的表
lua_getglobal(L, "mk");
size_t n = lua_objlen(L, -1);
for (int i = 1; i <= n; ++i) {
lua_pushinteger(L, i);
lua_gettable(L, -2);
printf("mk[%d] = %s\n", i, lua_tostring(L, -1));
lua_pop(L, 1);
}

printf("========================================\n");
int nIndex = lua_gettop(L);  // 取 table 索引值
lua_pushnil(L);  // nil 入栈作为初始 key
while (0 != lua_next(L, nIndex))
{
printf("mk
= %s\n", lua_tostring(L, -1));
lua_pop(L, 1);  // 弹出 value,让 key 留在栈顶
}
// 现在栈顶是 table

lua_pushstring(L, "=====>");
lua_setglobal(L, "kkm");

luaL_dofile(L, "test.lua");

lua_close(L);
system("pause");
return 0;
}


lua脚本部分

local lib = require "mylib"
print("gogo");

print(mk.key);
print(mk[1]);
print(kkm);

print(madd(100, 20))

print(lib.madd(120, 20))
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  lua c语言
相关文章推荐