2015-11-03 65 views
2

我嘗試使用string.find("中國", "中")。它在PC上成功,但在開發我的cocos-lua遊戲時失敗了。string.find在Android中的漢字失敗,但在開發cocos-lua遊戲時在PC上成功

在Android

string.find回報nil

Fristly,我認爲他們的編碼可能是diffent,所以我嘗試打印出自己的字節。

on 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

答案仍然是:

nil:nil

PS:string.find

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); 
} 
+0

'string.find(「中國」,「中」,1,真)'工作嗎?這會關閉模式匹配。 – lhf

+0

我試過這個,這不起作用。 – Sam

回答

2

的Lua的LUA實現不必Unicode字符正確的開箱即用支持的,但也有將解決好庫。我從來沒有使用過cocos2d,我不確定他們是否有任何附加組件來解決這個問題。但你可以嘗試使用這個:https://luarocks.org/modules/xavier-wang/luautf8。我曾經成功地使用過它。希望這可以幫助!

+1

我通過在lua中寫入kmp來自己比較utf8來解決這個問題。但我想知道爲什麼lua未能在Win32中使用find,但是使用Linux(Android)。 lua string.find的實現有什麼區別? – Sam

+0

string.match也可用 – Sam

相關問題