'lua_tostring adding a hyphen to the end of a string?
This function:
static int function_name(lua_State *L) {
const char* str = lua_tostring(L, 1);
const char* substr = lua_tostring(L, 2); // passing "how" results in "how-" ???
char *pch = strstr(str, substr);
if (pch != NULL)
lua_pushinteger(L, pch - str);
else
lua_pushnil(L);
return 1;
}
Invoking the function (i.e, function_name("hello how world", "how") produces this result. Why would lua_tostring return such an obfuscated result? This issue only occurs when I pass a string equal to the length of the substring I want to match to. For example
"hello how world", "hell" -> works fine
"hello how world", "hello" -> fails, thinks "hello-" is passed.
"hello how world", "ho" -> works fine
"hello how world", "how" -> fails, thinks "how-" is passed.
I'm printing substr immediately after I pull it from the stack to observe results. I don't believe any middle-men could mess it up.
Solution 1:[1]
Using PUC Lua version lua-5.4.0 compiled for X86-64 with MinGW, I registered the C function function_name to the Lua function TEST.
print(TEST("hello how world", "hell"))
print(TEST("hello how world", "hello"))
print(TEST("hello how world", "ho"))
print(TEST("hello how world", "how"))
The results seems correct:
0
0
6
6
If you are facing strange data corruption during the runtime of your program, you might have an pointer issue in some other places of your program, possibility in another thread.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Robert |
