string.find failed on Chinese character in Android but success on PC when developing cocos-lua game

回眸只為那壹抹淺笑 提交于 2019-12-12 17:26:41

问题


I try to use string.find("中国", "中"). It successed on PC but failed on Android when I develop my cocos-lua game.

on Android, string.find return nil

Fristly, I think their encoding may be diffent, so I try to print out their byte.

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)

text1:

228-184-173-229-155-189

text2:

228-184-173

The Answer is still:

nil:nil

PS: lua implementation of 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);
}

回答1:


Lua does not have proper support to unicode characters out of the box, but there are good libraries that will fix that. I have never used cocos2d and I'm unsure if they have any add-ons to deal with this. But you could try using this one:https://luarocks.org/modules/xavier-wang/luautf8. I have used it with success once. Hope this helps!



来源:https://stackoverflow.com/questions/33494176/string-find-failed-on-chinese-character-in-android-but-success-on-pc-when-develo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!