Ray Lee | 李宗叡
Learn or Die
Published in
3 min readOct 14, 2023

--

# 前言

紀錄 Lua script 中,pairs 與 ipairs 的差異

# ipairs

  • ipairs 主要用在 numeric table
  • 會從 index 1 開始
  • 任何 non-numeric key 都會被 ignore
  • 當 loop 到的 key 並非 上一個 key + 1 的話,停止 loop
  • 順序保證

# 從 index 1 開始

如下範例,會 return ‘bc’,因為從 1 開始

EVAL "
local t = {}
t[0] = 'a'
t[1] = 'b'
t[2] = 'c'

local result = ''
for key, value in ipairs(t) do result = result .. value end
return result
" 0

# unexpected index would halt

當 loop 到的 index 並非上一個 index + 1 的話,會停止 loop,如下 example 會 return ‘ab’,因為 t[4] 為 unexpected,所以停止了

EVAL "
local t = {}
t[1] = 'a'
t[2] = 'b'
t[4] = 'c'
t[5] = 'd'

local result = ''
for key, value in ipairs(t) do result = result .. value end
return result
" 0

同上的,如果 index 是 non-numeric,那也會停止 loop,如下範例會輸出 ‘ab’

EVAL "
local t = {}
t[1] = 'a'
t[2] = 'b'
t['test'] = 'c'
t[5] = 'd'

local result = ''
for key, value in ipairs(t) do result = result .. value end
return result
" 0

# pairs

  • pairs 主要用在 associative table
  • 順序不保證
  • 任何 key 都可以,因為就是走 key => value

# key => value base

pairs 專門用在 associative table 上,所以就沒有 numeric index 的限制,任何 key 都可以

如下 example,會輸出 ‘1a 2b testc 5d ‘

EVAL "
local t = {}
t[1] = 'a'
t[2] = 'b'
t['test'] = 'c'
t[5] = 'd'

local result = ''
for key, value in pairs(t) do result = result .. key .. value .. ' ' end
return result
" 0

如下 example,會輸出 ‘1a 2b testc 5d 0z ‘,這邊可以看到,順序是不保證的

EVAL "
local t = {}
t[0] = 'z'
t[1] = 'a'
t[2] = 'b'
t['test'] = 'c'
t[5] = 'd'

local result = ''
for key, value in pairs(t) do result = result .. key .. value .. ' ' end
return result
" 0

# 總結

  • 若對象是 numeric indexed array,像是 list,那請用 ipairs
  • 若對象是 associative array,像是 set or hash,那請用 pairs

--

--

Ray Lee | 李宗叡
Learn or Die

It's Ray. I do both backend and frontend, but more focus on backend. I like coding, and would like to see the whole picture of a product.