Skip to content

Commit

Permalink
add function wesnoth.read_file
Browse files Browse the repository at this point in the history
It can for example used to read map files.
  • Loading branch information
gfgtdf committed Feb 18, 2016
1 parent 322a2f7 commit 9c59311
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 1 deletion.
47 changes: 47 additions & 0 deletions src/scripting/lua_fileops.cpp
Expand Up @@ -100,6 +100,53 @@ int intf_have_file(lua_State *L)
else { lua_pushboolean(L, true); }
return 1;
}
/**
* Checks if a file exists (not necessarily a Lua script).
* - Arg 1: string containing the file name.
* - Ret 1: string
*/
int intf_read_file(lua_State *L)
{
std::string m = luaL_checkstring(L, 1);

std::string current_dir = "";
lua_Debug ar;
if(lua_getstack(L, 1, &ar)) {
lua_getinfo(L, "S", &ar);
if(ar.source[0] == '@') {
current_dir = filesystem::directory_name(std::string(ar.source + 1));
}
}
if(!resolve_filename(m, current_dir)) {
return luaL_argerror(L, -1, "file not found");
}
std::string p = filesystem::get_wml_location(m);
if(p.empty()) {
return luaL_argerror(L, -1, "file not found");
}
boost::scoped_ptr<std::istream> fs(filesystem::istream_file(p));
fs->exceptions(std::ios_base::goodbit);
size_t size = 0;
fs->seekg(0, std::ios::end);
if(!fs->good()) {
return luaL_error(L, "Error when reading file");
}
size = fs->tellg();
fs->seekg(0, std::ios::beg);
if(!fs->good()) {
return luaL_error(L, "Error when reading file");
}
luaL_Buffer b;
luaL_buffinit(L, &b);
//throws an exception if malloc failed.
char* out = luaL_prepbuffsize(&b, size);
fs->read(out, size);
if(!fs->good()) {
luaL_addsize(&b, size);
}
luaL_pushresult(&b);
return 1;
}

class lua_filestream
{
Expand Down
1 change: 1 addition & 0 deletions src/scripting/lua_fileops.hpp
Expand Up @@ -25,6 +25,7 @@ struct lua_State;
namespace lua_fileops {

int intf_have_file(lua_State*);
int intf_read_file(lua_State*);
int load_file(lua_State*);

} // end namespace lua_fileops
Expand Down
3 changes: 2 additions & 1 deletion src/scripting/lua_kernel_base.cpp
Expand Up @@ -263,7 +263,8 @@ lua_kernel_base::lua_kernel_base(CVideo * video)

static luaL_Reg const callbacks[] = {
{ "compare_versions", &intf_compare_versions },
{ "have_file", &lua_fileops::intf_have_file },
{ "have_file", &lua_fileops::intf_have_file },
{ "read_file", &lua_fileops::intf_read_file },
{ "textdomain", &lua_common::intf_textdomain },
{ "tovconfig", &lua_common::intf_tovconfig },
{ "get_dialog_value", &lua_gui2::intf_get_dialog_value },
Expand Down

0 comments on commit 9c59311

Please sign in to comment.