From 80789508b9655d25629223b9dcc84b4cfb77ce45 Mon Sep 17 00:00:00 2001 From: Alexander Date: Mon, 29 Jun 2020 15:29:03 -0400 Subject: Updates for mdoc Also more tests --- src/shared/lua_api/load_common.cpp | 51 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) (limited to 'src/shared/lua_api/load_common.cpp') diff --git a/src/shared/lua_api/load_common.cpp b/src/shared/lua_api/load_common.cpp index 1eca598..188cd30 100644 --- a/src/shared/lua_api/load_common.cpp +++ b/src/shared/lua_api/load_common.cpp @@ -5,6 +5,13 @@ extern "C" { #include #include } +//Open group +#include //for io.dir("file/path") +#include //required before sys/stat.h on windows +#include //for io.time("path/to.file") +#include +#include //For better errors + using namespace std::chrono; //Gets the time @@ -16,6 +23,45 @@ int get_time(lua_State* L){ return 1; } +char *epath; +size_t epathlen; +/*Add an io.dir(path) function, which lists all the files in (path)*/ +int dirpath(lua_State *L){ + if(!lua_isstring(L,-1)){ + lua_pushstring(L,"io.dir() requires a string as argument #1"); + lua_error(L); + } + size_t pathstrlen; + const char *pathstr = lua_tolstring(L,-1,&pathstrlen); + char tpathstr[pathstrlen + epathlen + 1 + 1]; //+1 for null, +1 for / + memcpy(tpathstr,epath,epathlen); + tpathstr[epathlen] = '/'; + memcpy(tpathstr+epathlen+1,pathstr,pathstrlen); + tpathstr[pathstrlen + epathlen + 1] = '\0'; + lua_pop(L,1); + DIR *dir; + struct dirent *ent; + dir = opendir(tpathstr); + if(dir == NULL){ + perror("Cannot open"); + lua_pushstring(L,"Failed to open directory: "); + lua_pushstring(L,tpathstr); + lua_concat(L,2); + lua_error(L); + } + int i = 1; + ent = readdir(dir); + lua_newtable(L); + while( (ent = readdir(dir)) != NULL){ + lua_pushinteger(L,i); + lua_pushstring(L,ent->d_name); + lua_settable(L,-3); + i++; + } + closedir(dir); + return 1; +} + void loadCommonLibs(lua_State* L){ lua_getglobal(L,"GAME"); lua_pushcfunction(L,make_crashy); @@ -23,6 +69,11 @@ void loadCommonLibs(lua_State* L){ lua_pop(L,1); lua_pushcfunction(L,get_time); lua_setglobal(L,"get_time"); + + lua_getglobal(L,"io"); + lua_pushcfunction(L,dirpath); + lua_setfield(L,-2,"dir"); + lua_pop(L,1); } void gameloop_common(lua_State* L){ -- cgit v1.2.3-70-g09d2