Skip to content

Instantly share code, notes, and snippets.

@ggzeng
Last active October 21, 2019 11:38
Show Gist options
  • Save ggzeng/4966df03db03017016698439aef79266 to your computer and use it in GitHub Desktop.
Save ggzeng/4966df03db03017016698439aef79266 to your computer and use it in GitHub Desktop.
在clang中执行lua脚本
cmake_minimum_required (VERSION 3.0)
project (lua_embed C)
find_package(Lua REQUIRED)
include_directories (
${CMAKE_CURRENT_BINARY_DIR}
${CMAKE_CURRENT_SOURCE_DIR}
${LUA_INCLUDE_DIR}
)
set (SOURCES
main.c
)
add_executable (${PROJECT_NAME} ${SOURCES})
target_link_libraries (${PROJECT_NAME} lua dl m)
local M = {}
local M_mt = { __index = M }
function M:new(start)
if self ~= M then
return nil, "First argument must be self" -- 使用冒号调用的方法都会有 self 变量
end
local o = setmetatable({}, M_mt) -- 调用o, 就和调用M一样(__index)
o._count = start
return o
end
setmetatable(M, { __call = M.new }) -- 当调用M()时,会实际调用M.new()函数
function M:add(amount)
self._count = self._count + amount
end
function M:subtract(amount)
self._count = self._count - amount
end
function M:increment()
self:add(1)
end
function M:decrement()
self:subtract(1)
end
function M:getval()
return self._count
end
function M_mt:__tostring()
return string.format("%d", self._count)
end
return M
cmod = require("counter")
c = cmod(0)
c:add(4)
c:decrement()
print("val=" .. c:getval())
c:subtract(-2)
c:increment()
print(c)
#include <stdio.h>
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>
int main(int argc, char **argv)
{
lua_State *L;
L = luaL_newstate();
luaL_openlibs(L);
if (luaL_dofile(L, "counter_test.lua")) { // 执行lua脚本
printf("Could not load file: %sn", lua_tostring(L, -1));
lua_close(L);
return 0;
}
lua_close(L);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment