cppToLua

#include"lua.hpp"
#include<iostream>
using namespace std;

void showStack(lua_State* st)
{
	int size = lua_gettop(st);
	cout << "=================== top ===================" << endl;
	while (size>0)
	{
		string value = lua_isstring(st, size) ? lua_tostring(st, size) : "table";

		cout << "index:" << size << "|| value::" << value << endl;
		size--;
	}
	cout << "=================== bottom ===================" << endl;
}


int main()//int argc,char** argv)
{
	//1.create Lua state
	lua_State* L = luaL_newstate();
	//2.load lua file
	luaL_loadfile(L, "test.lua");
	//3.run lua file
	lua_pcall(L, 0, 0, 0);
	//4.str push stack ,"hello lua " replace str
	lua_getglobal(L, "str");
	string str = lua_tostring(L, -1);
	showStack(L);
	//5. tab push stack top ,"{}" ,push name ,"" replace name
	lua_getglobal(L, "tab");
	lua_pushstring(L, "name");
	lua_gettable(L, -2);
	showStack(L);
	//6.push function;push lns;push 2ns
	lua_getglobal(L, "add");//获取函数,压入栈中
	lua_pushnumber(L, 10);//压入第一个参数
	lua_pushnumber(L, 20);
	showStack(L);
	//call function,pop 1ns.2ns.function,push ret(2:参数个数;1:返回结果个数)
	int msg = lua_pcall(L, 2, 1, 0);
	double ret = lua_tonumber(L, -1);
	showStack(L);
	//7.fix
	lua_pushnumber(L, 20210508);
	showStack(L);
	lua_setfield(L, 2, "id");
	lua_getglobal(L, "tab");
	lua_getfield(L, -1, "id");
	showStack(L);
	//8.add	
	lua_newtable(L);
	lua_pushstring(L, "add");
	showStack(L);
	lua_setfield(L, -2, "str");
	showStack(L);
	lua_close(L); 
	return 0;
}
上一篇:redis操作命令


下一篇:3