在lua中遍歷中文

2021-10-25 15:24:35 字數 2620 閱讀 3625

必要知識:字元編碼

lua中for的原理(描述中有不對的地方望見諒)

**例項:

local utf8changer =

local

function

chsize

(char)

ifnot char then

--print("not char")

return

0elseif char >

240then

return

4elseif char >

225then

return

3elseif char >

192then

return

2else

return

1end

end-- 計算utf8字串字元數, 各種字元都按乙個字元計算

-- 例如utf8len("1你好") => 3

local

function

utf8len

(str)

local len =

0local currentindex =

1while currentindex <=

#str do

local char = string.

byte

(str, currentindex)

currentindex = currentindex +

chsize

(char)

len = len +

1end

return len

end-- 擷取utf8 字串

-- str: 要擷取的字串

-- startchar: 開始字元下標,從1開始

-- numchars: 要擷取的字元長度

local

function

utf8sub

(str, startchar, numchars)

local startindex =

1while startchar >1do

local char = string.

byte

(str, startindex)

--起始的位置

startindex = startindex +

chsize

(char)

startchar = startchar -

1end

local currentindex = startindex

while numchars >

0and currentindex <=

#str do

local char = string.

byte

(str, currentindex)

currentindex = currentindex +

chsize

(char)

numchars = numchars -

1end

return str:

sub(startindex, currentindex -1)

endlocal

function

ipairs

(str)

local startindex =1;

local key =

0local _str = str;

return

function()

if str ==

nilor

#str ==

0then

return

nilend

local char = string.

byte

(str, startindex)

local len =

chsize

(char)

if len ==

0then

return

nilend

local currentindex = startindex + len;

local value = _str:

sub(startindex, currentindex -1)

startindex = startindex + len

key = key +1;

return key, value

endendutf8changer.utf8len = utf8len

utf8changer.utf8sub = utf8sub

utf8changer.ipairs = ipairs

return utf8changer

local utf8changer =

require

("utf8changer"

)local str =

"123,這是我的測試**。"

local ipairs = utf8changer.ipairs

for index, value in

ipairs

(str)

doprint

(index , value)

end

XLua 在Lua中遍歷C 的Dictionary

前些日子在處理一段客戶端資料時遇到這樣乙個問題,嘗試了各種的迴圈遍歷,結果都是不行,後來發現這段資料是c 的dictionary。我們在lua中可以通過獲取迭代器的方式來遍歷c 的dictionary。廢話不多說,直接上 local playerinfo cs.sg.playerdata.insta...

c中遍歷lua表結構

c中遍歷lua表結構 進行下面步驟前先將 table 壓入棧頂 intnindex lua gettop plua 取 table 索引值 lua pushnil plua nil 入棧作為初始 key while 0 lua next plua,nindex 現在棧頂是 table lua nex...

c中遍歷lua表結構

進行下面步驟前先將 table 壓入棧頂 intnindex lua gettop plua 取 table 索引值 lua pushnil plua nil 入棧作為初始 key while 0 lua next plua,nindex 現在棧頂是 table lua next 這個函式的工作過程...