乐闻世界logo
搜索文章和话题

How to iterate through table in Lua?

1个答案

1

In Lua, iterating over tables (which serve as the data structure for arrays or hash tables) can be achieved through multiple methods, with pairs() and ipairs() being the most commonly used functions.

1. Using pairs()

The pairs() function iterates over all elements in a table, including key-value pairs with non-numeric indices. This function is ideal for traversing hash tables or other tables that contain non-sequential keys.

Example code:

lua
local person = {name = "张三", age = 30, city = "北京"} for key, value in pairs(person) do print(key, value) end

Output will be:

shell
name 张三 age 30 city 北京

In this example, we create a table containing personal information and use pairs() to iterate over it, printing all key-value pairs.

2. Using ipairs()

The ipairs() function iterates over table elements with numeric indices, typically used for arrays. It starts iteration from index 1 and continues until it encounters the first nil value.

Example code:

lua
local fruits = {"苹果", "香蕉", "橙子"} for index, fruit in ipairs(fruits) do print(index, fruit) end

Output will be:

shell
1 苹果 2 香蕉 3 橙子

In this example, we create an array of fruits and use ipairs() to iterate over it, printing each fruit along with its corresponding index.

Usage Scenario Comparison

  • Use ipairs() when traversing an array with consecutive numeric indices.
  • Use pairs() when traversing a table that may contain string keys or non-consecutive numeric indices.

Understanding how to effectively use these functions and their distinctions can help you handle and manipulate table data more efficiently in Lua programming.

2024年8月8日 13:50 回复

你的答案