lua
cpp 调用 lua
项目结构 :
. ├── CMakeLists.txt ├── hello.lua └── main.cpp
CMakeLists.txt:
cmake_minimum_required(VERSION 3.19)
project(lua_cpp)
set(CMAKE_CXX_STANDARD 17)
include(FindLua)
find_package(Lua REQUIRED)
add_executable(lua_cpp main.cpp)
target_link_libraries(${PROJECT_NAME} PRIVATE ${LUA_LIBRARIES})
target_include_directories(${PROJECT_NAME} PRIVATE ${LUA_INCLUDE_DIR})
hello.lua:
str = "Hello, Lua"
tbl = { name = "zhang", id = 2018 }
function add(a, b)
return (a + b)*2
end
print(str)
cpp:
#include <iostream>
#include <lua.hpp>
#include <cassert>
#include <string>
using namespace std;
int main() {
auto L = luaL_newstate();
auto bRet = luaL_loadfile(L, "hello.lua");
lua_pcall(L,0,0,0);
lua_getglobal(L, "str");
cout<<lua_tostring(L, -1)<<endl;
lua_getglobal(L, "add");
lua_pushnumber(L, 10);
lua_pushnumber(L, 20);
lua_pcall(L, 2,1,0);
cout<<lua_tonumber(L, -1);
lua_getglobal(L, "print");
lua_pushnumber(L, 20);
lua_pcall(L, 1,1,0);
lua_close(L);
return 0;
}