diff options
Diffstat (limited to 'Runtime/Scripting/IO/IO.bind.cpp')
-rw-r--r-- | Runtime/Scripting/IO/IO.bind.cpp | 80 |
1 files changed, 77 insertions, 3 deletions
diff --git a/Runtime/Scripting/IO/IO.bind.cpp b/Runtime/Scripting/IO/IO.bind.cpp index ba5691f..a46b110 100644 --- a/Runtime/Scripting/IO/IO.bind.cpp +++ b/Runtime/Scripting/IO/IO.bind.cpp @@ -1,12 +1,24 @@ #include "Runtime/Lua/LuaHelper.h" #include "Runtime/Debug/Log.h" +#include "Runtime/Common/DataBuffer.h" #include "Runtime/FileSystem/FileJobs.h" +#include <fstream> + +using namespace std; +using namespace LuaBind; + +enum EFileMode +{ + FileMode_Text, + FileMode_Binary, +}; + // IO.ReadFiles({}, callback) int ReadFilesAsync(lua_State* L) { LUA_BIND_STATE(L); - LUA_BIND_CHECK(L, "TF"); + LUA_BIND_CHECK(L, "TF!"); std::vector<std::string> files; for (int i = 1; true; ++i) @@ -30,9 +42,66 @@ int ReadFilesAsync(lua_State* L) return 0; } +// IO.ReadFile(path[,mode]) +// return DataBuffer +int ReadFile(lua_State* L) +{ + LUA_BIND_STATE(L); + LUA_BIND_CHECK(L, "SN!|S!"); + + const char* path = state.GetValue(1, ""); + int mode = state.GetValue<int>(2, EFileMode::FileMode_Binary); + + bool isTextFile = mode == EFileMode::FileMode_Text; + bool isBinaryFile = mode == EFileMode::FileMode_Binary; + + int openMode = 0; + //if (isBinaryFile) + openMode |= ios::binary; + + std::ifstream file = ifstream(path, openMode); + if (!file.is_open()) + { + log_error(string("Can't read file. ") + path); + state.PushNil(); + return 1; + } + + std::streampos size = file.tellg(); + file.seekg(0, std::ios::end); + size = file.tellg() - size; + if (size == 0) + { + log_error(string("File is Empty. ") + path); + state.PushNil(); + return 1; + } + file.seekg(0, std::ios::beg); + + int bufSize = size; + if (isTextFile) + bufSize += 1; // \0 + + DataBuffer* buffer = new DataBuffer(state.GetVM()); + buffer->type = isBinaryFile ? EDataBufferType::DataBufferMode_Binary : EDataBufferType::DataBufferMode_Text; + buffer->data = new char[bufSize]; + buffer->length = bufSize; + + file.read(buffer->data, size); + file.close(); + + if (isTextFile) + buffer->data[bufSize - 1] = '\0'; + + buffer->PushUserdata(state); + + return 1; +} + static luaL_Reg ioFuncs[] = { - {"ReadFilesAsync", ReadFilesAsync}, - {0, 0} + { "ReadFilesAsync", ReadFilesAsync }, + { "ReadFile", ReadFile }, + { 0, 0 } }; int luaopen_GameLab_IO(lua_State* L) @@ -47,5 +116,10 @@ int luaopen_GameLab_IO(lua_State* L) state.RegisterMethods(ioFuncs); + LUA_BIND_REGISTER_ENUM(state, "EFileMode", + { "Binary", EFileMode::FileMode_Binary}, + { "Text", EFileMode::FileMode_Text} + ); + return 1; }
\ No newline at end of file |