ExperimentalGear/scripts/core/game.lua

109 lines
2.5 KiB
Lua

---Drewol, what are you doing? Why is there no game.LOGGER_DEBUG?
game.LOGGER_DEBUG = 0
-- add missing inputs
game.MOUSE_LEFT = 0
game.MOUSE_RIGHT = 1
game.MOUSE_MIDDLE = 2
game.KNOB_LEFT = 0
game.KNOB_RIGHT = 1
--file reader utility functions
require("core.filesys")
game.file = {
__name = "game.file"
}
---Get game path
---@return string, string # path, separator
local function get_game_path()
return debug.getinfo(1,"S").source:sub(2):match("(.*)([\\/])skins") -- this is very hacky :)
end
---Read bytes out of binary file
---@param _file file*
---@return integer[]
local function read_bytes(_file)
local out = {}
repeat
local buffer = _file:read(4*1024)
for c in (buffer or ''):gmatch(".") do
table.insert(out, c:byte())
end
until not buffer
return out
end
---Read a file in the game folder
---@param path string # relative path to game file
---@param mode? openmode # default "r"
---@return file*? lines
---@return string? errmsg
function game.file.open(path, mode)
mode = mode or "r"
local gamepath, sep = get_game_path()
return io.open(gamepath .. sep .. path, mode)
end
---Read a file in the game folder
---@param path string # relative path to game file
---@return string? text
---@return string? errmsg
function game.file.readfile(path)
local gamepath, sep = get_game_path()
local out
local f, err = io.open(gamepath .. sep .. path)
if not f then
return nil, err
end
out = f:read("a")
f:close()
return out
end
---Read a file in the game folder
---@param path string # relative path to game file
---@return integer[]? bytes
---@return string? errmsg
function game.file.readbinary(path)
local gamepath, sep = get_game_path()
local out
local f, err = io.open(gamepath .. sep .. path, "rb")
if not f then
return nil, err
end
out = read_bytes(f)
f:close()
return out
end
--- Check if a file or directory exists at the path
---@param path string # relative path to game file
---@return boolean # file exists
---@return string? # error message
function game.file.exists(path)
local gamepath, sep = get_game_path()
path = gamepath .. sep .. path
return filesys.exists(path)
end
--- Check if a directory exists in this path
---@param path string # relative path to game directory
---@return boolean # directory exists
---@return string? # error message
function game.file.isdir(path)
-- "/" works on both Unix and Windows
return game.file.exists(path .. "/")
end