lua_lib_in_c_playground/uname.c

82 lines
1.8 KiB
C
Raw Permalink Normal View History

2024-08-17 23:26:07 +09:00
#define _GNU_SOURCE 1
#include <string.h>
#include <stdio.h>
#include <err.h>
#include <errno.h>
#include "uname.h"
#include <lauxlib.h>
#include <lua.h>
#include <sys/utsname.h>
#define ERRBUF_SIZE 1024
static int l_numid(lua_State *L) {
lua_Number x = luaL_checknumber(L, 1);
printf("%f\n", x);
lua_pushnumber(L, x);
return 1;
}
/*
* Add one
*/
long long plus_one(int x) {
return x + 1;
}
static int l_plus_one(lua_State *L) {
// argument number check is not conventional in lua?
int argc = lua_gettop(L);
if (argc != 1)
return luaL_error(L, "Invalid number of argument");
// Type check and get
lua_Integer x = luaL_checkinteger(L, 1);
lua_Integer result = plus_one(x);
// Push the result
lua_pushinteger(L, result);
// How many elements from the top is return value
return 1;
}
static int l_uname(lua_State *L) {
struct utsname name;
if (uname(&name)) {
char errbuf[ERRBUF_SIZE];
if (strerror_r(errno, errbuf, ERRBUF_SIZE))
perror("Error while making error msg");
return luaL_error(L, errbuf);
}
lua_newtable(L);
lua_pushstring(L, "sysname");
lua_pushstring(L, name.sysname);
lua_settable(L, -3);
lua_pushstring(L, "machine");
lua_pushstring(L, name.machine);
lua_settable(L, -3);
lua_pushstring(L, "release");
lua_pushstring(L, name.release);
lua_settable(L, -3);
lua_pushstring(L, "version");
lua_pushstring(L, name.version);
lua_settable(L, -3);
return 1;
}
static const struct luaL_Reg llib_uname [] = {
{"uname", l_uname},
{"numid", l_numid},
{"plusone", l_plus_one},
{NULL, NULL},
};
// for `require`
int luaopen_uname(lua_State *L) {
luaL_newlib(L, llib_uname);
return 1;
}