#include <iostream>
#include <string.h>
using namespace std;
extern "C"
{
#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"
}
void main()
{
//1.创建一个state
lua_State *L = luaL_newstate();
//2.入栈操作
lua_pushstring(L, "I am so cool~");
lua_pushnumber(L,20);
//3.取值操作
if( lua_isstring(L,1)){ //判断是否可以转为string
cout<<lua_tostring(L,1)<<endl; //转为string并返回
}
if( lua_isnumber(L,2)){
cout<<lua_tonumber(L,2)<<endl;
}
//4.关闭state
lua_close(L);
return ;
}
CMAKE_MINIMUM_REQUIRED(VERSION 3.14)
#指定项目名称
PROJECT(luaDemo)
#将hello.cpp 赋值给SOURCE 变量
SET(SOURCE ${PROJECT_SOURCE_DIR}/demo.cpp)
#指定头文件目录
INCLUDE_DIRECTORIES(../src)
#指定链接库文件目录
LINK_DIRECTORIES(${PROJECT_SOURCE_DIR}/lib)
#将hello.cpp生成可执行文件hello
ADD_EXECUTABLE(luaDemo ${SOURCE})
#指定hello 链接库myprint
TARGET_LINK_LIBRARIES(luaDemo lua51)
注意,exe执行时要与lua51.dll放在一起.
str = "I am so cool"
tbl = {name = "shun", id = 20114442}
function add(a,b)
return a + b
end
#include <iostream>
#include <string.h>
using namespace std;
extern "C"
{
#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"
}
double luaAdd(lua_State *L,double a, double b){
double fValue=0;
//6.读取函数
lua_getglobal(L, "add"); // 获取函数,压入栈中
lua_pushnumber(L, a); // 压入第一个参数
lua_pushnumber(L, b); // 压入第二个参数
int iRet= lua_pcall(L, 2, 1, 0);// 调用函数,调用完成以后,会将返回值压入栈中,2表示参数个数,1表示返回结果个数。
if (iRet) // 调用出错
{
const char *pErrorMsg = lua_tostring(L, -1);
cout << pErrorMsg << endl;
lua_close(L);
return -4;
}
if (lua_isnumber(L, -1)) //取值输出
{
fValue = lua_tonumber(L, -1);
cout << "Result is " << fValue << endl;
}
return fValue;
}
int main()
{
//1.创建Lua状态
lua_State *L = luaL_newstate();
if (L == NULL)
{
return -1;
}
//2.加载lua文件
int bRet = luaL_loadfile(L,"param.lua");
if(bRet)
{
cout<<"load file error"<<endl;
return -2;
}
//3.运行lua文件
bRet = lua_pcall(L,0,0,0);
if(bRet)
{
cout<<"pcall error"<<endl;
return -3;
}
//4.读取变量
lua_getglobal(L,"str");
string str = lua_tostring(L,-1);
cout<<"str = "<<str.c_str()<<endl; //str = I am so cool~
//5.读取table
lua_getglobal(L,"tbl");
lua_getfield(L,-1,"name");
str = lua_tostring(L,-1);
cout<<"tbl:name = "<<str.c_str()<<endl; //tbl:name = shun
luaAdd(L,10,20);
luaAdd(L,100,200);
//至此,栈中的情况是:
//=================== 栈顶 ===================
// 索引 类型 值
// 4 int: 30
// 3 string: shun
// 2 table: tbl
// 1 string: I am so cool~
//=================== 栈底 ===================
//7.关闭state
lua_close(L);
return 0;
}
参考:https://blog.csdn.net/shun_fzll/article/details/39120965
本文分享自 传输过程数值模拟学习笔记 微信公众号,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。
本文参与 腾讯云自媒体同步曝光计划 ,欢迎热爱写作的你一起参与!