Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * returns an absolute path from a relative file name
- */
- #ifdef __cplusplus
- #include "lua.hpp"
- #else
- #include "lua.h"
- #include "lualib.h"
- #include "lauxlib.h"
- #endif
- #include <math.h>
- #include <stdlib.h>
- #include <string.h>
- #include <errno.h>
- #include "libluaph1.h"
- #ifdef __cplusplus
- extern "C"{
- #endif
- static int os_setenv(lua_State* L) {
- const char* name = luaL_checkstring(L, 1);
- const char* value = luaL_checkstring(L, 2);
- int len = strlen(name) + strlen(value) + 2; //adding one char for '=' and another for '\0'
- char buffer[len];
- strcpy(buffer, name);
- strcat(buffer, "=");
- strcat(buffer, value);
- buffer[len] = 0;
- int res = putenv(buffer);
- printf("env (%d): %s, %s\n", res, buffer, getenv(name));
- if (res != 0) {
- lua_pushnil(L);
- lua_pushfstring(L, "unable to set environment variable '%s', errno %d : %s", name, errno, strerror(errno));
- return 2;
- }
- lua_pushnumber(L, res);
- return 1;
- }
- static int os_getenv(lua_State* L) {
- const char* name = luaL_checkstring(L, 1);
- char *buffer;
- printf("name: %s\n", name);
- buffer = getenv(name);
- printf("env: %s\n", buffer);
- if (buffer == NULL) {
- lua_pushnil(L);
- lua_pushfstring(L, "unable to get environment variable '%s'", name);
- return 2;
- }
- lua_pushstring(L, buffer);
- return 1;
- }
- static int os_realpath(lua_State* L) {
- char result[PH_PATH_MAX];
- int ok;
- const char* path = luaL_checkstring(L, 1);
- #ifdef __MINGW32__
- ok = (_fullpath(result, path, PH_PATH_MAX) != NULL);
- #else
- ok = (realpath(path, result) != NULL);
- #endif
- if (!ok) {
- lua_pushnil(L);
- lua_pushfstring(L, "unable to fetch real path of '%s', errno %d : %s", path, errno, strerror(errno));
- return 2;
- }
- lua_pushstring(L, result);
- return 1;
- }
- //library to be registered
- static const struct luaL_Reg libluaph1 [] = {
- {"realpath", os_realpath},
- {"setenv", os_setenv},
- {"getenv", os_getenv},
- {NULL, NULL} /* sentinel */
- };
- //name of this function is not flexible
- int luaopen_libluaph1 (lua_State *L){
- luaL_newlib(L, libluaph1);
- return 1;
- }
- #ifdef __cplusplus
- }
- #endif
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement