mirror of
https://github.com/luanti-org/luanti.git
synced 2025-06-27 16:36:03 +00:00
Script: Enforce type checks if not nil (#9748)
* Script: Enforce type checks if not nil
This commit is contained in:
parent
515d38a702
commit
be71e70a91
4 changed files with 72 additions and 56 deletions
|
@ -33,10 +33,9 @@ extern "C" {
|
|||
#define CHECK_TYPE(index, name, type) { \
|
||||
int t = lua_type(L, (index)); \
|
||||
if (t != (type)) { \
|
||||
std::string traceback = script_get_backtrace(L); \
|
||||
throw LuaError(std::string("Invalid ") + (name) + \
|
||||
" (expected " + lua_typename(L, (type)) + \
|
||||
" got " + lua_typename(L, t) + ").\n" + traceback); \
|
||||
" got " + lua_typename(L, t) + ")."); \
|
||||
} \
|
||||
}
|
||||
#define CHECK_POS_COORD(name) CHECK_TYPE(-1, "position coordinate '" name "'", LUA_TNUMBER)
|
||||
|
@ -457,12 +456,22 @@ size_t read_stringlist(lua_State *L, int index, std::vector<std::string> *result
|
|||
Table field getters
|
||||
*/
|
||||
|
||||
bool check_field_or_nil(lua_State *L, int index, int type, const char *fieldname)
|
||||
{
|
||||
if (lua_isnil(L, index))
|
||||
return false;
|
||||
|
||||
CHECK_TYPE(index, std::string("field \"") + fieldname + '"', type);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool getstringfield(lua_State *L, int table,
|
||||
const char *fieldname, std::string &result)
|
||||
{
|
||||
lua_getfield(L, table, fieldname);
|
||||
bool got = false;
|
||||
if(lua_isstring(L, -1)){
|
||||
|
||||
if (check_field_or_nil(L, -1, LUA_TSTRING, fieldname)) {
|
||||
size_t len = 0;
|
||||
const char *ptr = lua_tolstring(L, -1, &len);
|
||||
if (ptr) {
|
||||
|
@ -479,7 +488,8 @@ bool getfloatfield(lua_State *L, int table,
|
|||
{
|
||||
lua_getfield(L, table, fieldname);
|
||||
bool got = false;
|
||||
if(lua_isnumber(L, -1)){
|
||||
|
||||
if (check_field_or_nil(L, -1, LUA_TNUMBER, fieldname)) {
|
||||
result = lua_tonumber(L, -1);
|
||||
got = true;
|
||||
}
|
||||
|
@ -492,7 +502,8 @@ bool getboolfield(lua_State *L, int table,
|
|||
{
|
||||
lua_getfield(L, table, fieldname);
|
||||
bool got = false;
|
||||
if(lua_isboolean(L, -1)){
|
||||
|
||||
if (check_field_or_nil(L, -1, LUA_TBOOLEAN, fieldname)){
|
||||
result = lua_toboolean(L, -1);
|
||||
got = true;
|
||||
}
|
||||
|
@ -511,17 +522,6 @@ size_t getstringlistfield(lua_State *L, int table, const char *fieldname,
|
|||
return num_strings_read;
|
||||
}
|
||||
|
||||
std::string checkstringfield(lua_State *L, int table,
|
||||
const char *fieldname)
|
||||
{
|
||||
lua_getfield(L, table, fieldname);
|
||||
CHECK_TYPE(-1, std::string("field \"") + fieldname + '"', LUA_TSTRING);
|
||||
size_t len;
|
||||
const char *s = lua_tolstring(L, -1, &len);
|
||||
lua_pop(L, 1);
|
||||
return std::string(s, len);
|
||||
}
|
||||
|
||||
std::string getstringfield_default(lua_State *L, int table,
|
||||
const char *fieldname, const std::string &default_)
|
||||
{
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue