works:programmer:cpp:lua-library-test
Написание Си библиотеки для Lua
- lualibtest.c
#include <unistd.h> #include <time.h> #include <math.h> #include <lua.h> #include <lauxlib.h> #include <lualib.h> static int api_Sleep(lua_State* L) { int argc = lua_gettop(L); if (argc != 1) { lua_pushstring(L, "sleep function requres an argument"); lua_error(L); } lua_Number argv1 = lua_tonumber(L, 1); if (argv1 <= 0) { lua_pushstring(L, "sleep funtion requires number, greather than zero"); lua_error(L); } int sleepTime = floor(argv1 * 1000000); usleep(sleepTime); return 0; } static int api_Version(lua_State* L) { lua_pushstring(L, "LibTest 1.0.0"); lua_pushnumber(L, 100); return 2; } static const struct luaL_Reg LuaLibCtx [] = { {"sleep", api_Sleep}, {"version", api_Version}, {NULL, NULL} }; int extern luaopen_libtest(lua_State *L) { luaL_newlib(L, LuaLibCtx); return 1; }
- makefile
# LIBS="$(PREFIX)/" INCS="$(PREFIX)/include/lua5.3/" libtest.so: lualibtest.c gcc -shared -I$(INCS) $< -o $@
local lib = assert(require("libtest")) local nixnow = function() return os.time(os.date("!*t")) end local a = nixnow() print(lib.version()) lib.sleep(5) print("Test done! " .. tostring(nixnow()-a))
works/programmer/cpp/lua-library-test.txt · Последнее изменение: 2022/10/31 02:31 — 127.0.0.1