我尝试使用string.find("中国", "中")
。我开发cocos-lua游戏时,在PC上成功,但在Android上失败。
在 Android 上,string.find
返回 nil
首先,我认为它们的编码可能不同,所以我尝试打印出它们的字节。
Android 上:text1:“中国”,text2:“中”。
local text1 = self.__editBox2:getText()
local text2 = self.__editBox3:getText()
local code1 = ""
for i = 1, string.len(text1) do
code1 = code1 .. "-" .. tostring(string.byte(text1, i))
end
local code2 = ""
for i = 1, string.len(text2) do
code2 = code2 .. "-" .. tostring(string.byte(text1, i))
end
self.__editBox2:setText(code1)
self.__editBox3:setText(code2)
local a, b = string.find(text1, text2)
local data = tostring(a) .. ":" .. tostring(b)
self.__editBox1:setText(data)
文本1:
228-184-173-229-155-189
文本2:
228-184-173
答案仍然是:
零:零
PS:string.find
的lua实现
static int str_find_aux (lua_State *L, int find) {
size_t l1, l2;
const char *s = luaL_checklstring(L, 1, &l1);
const char *p = luaL_checklstring(L, 2, &l2);
ptrdiff_t init = posrelat(luaL_optinteger(L, 3, 1), l1) - 1;
if (init < 0) init = 0;
else if ((size_t)(init) > l1) init = (ptrdiff_t)l1;
if (find && (lua_toboolean(L, 4) || /* explicit request? */
strpbrk(p, SPECIALS) == NULL)) { /* or no special characters? */
/* do a plain search */
const char *s2 = lmemfind(s+init, l1-init, p, l2);
if (s2) {
lua_pushinteger(L, s2-s+1);
lua_pushinteger(L, s2-s+l2);
return 2;
}
}
else {
MatchState ms;
int anchor = (*p == '^') ? (p++, 1) : 0;
const char *s1=s+init;
ms.L = L;
ms.src_init = s;
ms.src_end = s+l1;
do {
const char *res;
ms.level = 0;
if ((res=match(&ms, s1, p)) != NULL) {
if (find) {
lua_pushinteger(L, s1-s+1); /* start */
lua_pushinteger(L, res-s); /* end */
return push_captures(&ms, NULL, 0) + 2;
}
else
return push_captures(&ms, s1, res);
}
} while (s1++ < ms.src_end && !anchor);
}
lua_pushnil(L); /* not found */
return 1;
}
static int str_find (lua_State *L) {
return str_find_aux(L, 1);
}
最佳答案
Lua 没有对 unicode 字符提供适当的支持,但是有一些很好的库可以解决这个问题。我从未使用过 cocos2d,我不确定他们是否有任何附加组件来处理这个问题。但你可以尝试使用这个:https://luarocks.org/modules/xavier-wang/luautf8 。我用过一次就成功了。希望这有帮助!
关于lua - 开发cocos-lua游戏时,Android中string.find中文字符失败,PC上成功,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33494176/