此函数:
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;
}
调用函数(即function_name("hello how world", "how"
(会产生此结果。为什么lua_tostring
会返回如此模糊的结果?只有当我传递一个等于我想要匹配的子字符串长度的字符串时,才会出现这个问题
"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.
从堆栈中取出substr
以观察结果后,我立即打印它。我不相信任何中间人会把事情搞砸。
使用MinGW为X86-64编译的PUC Lua版本lua-5.4.0
,我将C函数function_name
注册到Lua函数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"))
结果似乎是正确的:
0
0
6
6
如果您在程序运行期间遇到奇怪的数据损坏,您可能在程序的其他位置出现指针问题,也可能在另一个线程中出现。