Modernize lua read (part 2 & 3): C++ templating assurance (#7410)
[oweals/minetest.git] / src / script / common / helper.cpp
1 /*
2 Minetest
3 Copyright (C) 2018 nerzhul, Loic Blot <loic.blot@unix-experience.fr>
4
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 GNU Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19
20 #include "helper.h"
21 #include <cmath>
22 #include <sstream>
23 #include "c_types.h"
24
25 bool LuaHelper::isNaN(lua_State *L, int idx)
26 {
27         return lua_type(L, idx) == LUA_TNUMBER && std::isnan(lua_tonumber(L, idx));
28 }
29
30 /*
31  * Read template functions
32  */
33 template <> bool LuaHelper::readParam(lua_State *L, int index)
34 {
35         return lua_toboolean(L, index) != 0;
36 }
37
38 template <> bool LuaHelper::readParam(lua_State *L, int index, const bool &default_value)
39 {
40         if (lua_isnil(L, index))
41                 return default_value;
42
43         return lua_toboolean(L, index) != 0;
44 }
45
46 template <> float LuaHelper::readParam(lua_State *L, int index)
47 {
48         if (isNaN(L, index))
49                 throw LuaError("NaN value is not allowed.");
50
51         return (float)luaL_checknumber(L, index);
52 }
53
54 template <> std::string LuaHelper::readParam(lua_State *L, int index)
55 {
56         std::string result;
57         const char *str = luaL_checkstring(L, index);
58         result.append(str);
59         return result;
60 }
61
62 template <>
63 std::string LuaHelper::readParam(
64                 lua_State *L, int index, const std::string &default_value)
65 {
66         std::string result;
67         const char *str = lua_tostring(L, index);
68         if (str)
69                 result.append(str);
70         else
71                 result = default_value;
72         return result;
73 }