c - Integer reduces to string when accessing via tostring/checkstring? -


do integral values reduce down strings in lua? i've tried track down bug full hour, when realized numbers same strings, given following code:

main.c:

#include <stdio.h> #include "lua.h" #include "lauxlib.h" #include "lualib.h"  int ex_dummyfunc(lua_state* l) {     const char* first = lual_checkstring(l, 1);     int second = lual_checkinteger(l, 2);     printf("first = %s, second = %d\n", first, second);     return 0; }  int main(int argc, char *argv[]) {     lua_state *l = lual_newstate();     lual_openlibs(l);     lua_register(l, "dummyfunc", ex_dummyfunc);     if(argc > 1)     {         if(lual_dofile(l, argv[1]) == 1)         {             fprintf(stderr, "error: %s\n", lua_tostring(l, 1));         }     }     lua_close(l);     return 0; } 

test.lua:

dummyfunc("stuff", 42) dummyfunc(42, 8) dummyfunc(82, "stuff") 

output:

first = stuff, second = 42 first = 42, second = 8 error: test.lua:4: bad argument #2 'dummyfunc' (number expected, got string) 

_edit_:

thanks answer kevin ballard, , googling on how typechecking performed internally, i've noticed lual_checktype, allows token-based type enforcement. so, enforce string argument, function ex_dummyfunc needs edited way:

int ex_dummyfunc(lua_state* l) {     lual_checktype(l, 1, lua_tstring);     const char* first = lual_checkstring(l, 1);     int second = lual_checkinteger(l, 2);     printf("first = %s, second = %d\n", first, second);     return 0; } 

why lua not throw type error on second call dummyfunc?

according documentation:

const char *lual_checkstring (lua_state *l, int narg);

checks whether function argument narg string , returns string.

this function uses lua_tolstring result, conversions , caveats of function apply here.

in documentation lua_tolstring says "the lua value must string or number". no, lua not store strings , numbers same internally, yes, tend convert between 2 necessary.


Comments

Popular posts from this blog

java - SNMP4J General Variable Binding Error -

windows - Python Service Installation - "Could not find PythonClass entry" -

Determine if a XmlNode is empty or null in C#? -