Jump to content

Lua/Tables

From Wikiversity
< Lua

Lua modules based on the Scribunto/Lua extension are stored in resource pages using the Module: namespace. Each module uses a table to hold functions and variables, and that containing table is returned at the end of the module code.[1] Tables are associative arrays or collections of data with key / value pairs that may be used to hold, organize and access data. This lesson will show you how to use tables in your scripts.

Prerequisites

[edit | edit source]

This lesson assumes you have already completed the Functions lesson.

Console to learn Lua

[edit | edit source]
  1. In Module:Sandbox, click Edit source without modifying the existing code.
  2. Scroll down until Debug console at the end of the page.
  3. Paste the following entire function and its call together then validate once by Enter: ↲
local function tableToString(tab) -- pretty stringify input table
    local key; local val; local sep; local res = {':'} -- left margin
    for key, val in pairs(tab) do -- Iterates each pair key val
        if #res % 5 == 0 then sep = '\n:' else sep = '. ' end -- separator
        if tonumber(key) then -- numerical index of table?
        	res[#res + 1] = 'table[' .. key .. '] is ' .. val .. sep -- [index]
        else -- alpha key without white separator
        	res[#res + 1] = 'table.' .. key .. ' is ' .. val .. sep -- dot 𝛼
        end
    end
    return table.concat(res) -- concatenation more efficient than .. operator
end
local lstNum = {10, 20, 30}
print(tableToString(lstNum))

The result should be:

:table[1] is 10. table[2] is 20. table[3] is 30.

Let's define a dictionary of Asian languages:

local lstAsian = {ja = "日本語", ko = "한국어", zh = "中文"}
print(lstNum[2])
print(lstAsian.ja)
print(tableToString(lstAsian))

The Debug console supports Unicode:

20
日本語
:table.ja is 日本語. table.zh is 中文. table.ko is 한국어.

CAUTION: Iterator pairs(tab) may iterate in arbitrary order.

Note: press upwards arrow ↑ for the historic in the Debug console.

Compare with the standard mw.logObject(table):

mw.logObject(lstAsian)
table#1 {
    ["ja"] = "日本語",
    ["ko"] = "한국어",
    ["zh"] = "中文",
}

Create a Lua Script with Tables

[edit | edit source]

To create a Lua script with tables:

  1. Go to the top of Module:Sandbox in the editor.
  2. Replace the existing code pasting the following Lua code without clicking on Publish changes.
local p = {} 
local function tableToString(tab) -- pretty stringify input table
    local key; local val; local sep; local res = {':'} -- left margin
    for key, val in pairs(tab) do -- Iterates each pair key val
        if #res % 5 == 0 then sep = '\n:' else sep = '. ' end -- separator
        if tonumber(key) then -- numerical index of table?
        	res[#res + 1] = 'table[' .. key .. '] is ' .. val .. sep -- [index]
        else -- alpha key without white separator
        	res[#res + 1] = 'table.' .. key .. ' is ' .. val .. sep -- dot alpha
        end
    end
    return table.concat(res) -- concatenation more efficient than string `..` operator
end
function p.sequence() return ';sequence\n' .. tableToString({10, 20, 30}) end -- numerical sequence
function p.dictionary() -- returns a dictionary of language codes -> English names
    local lstLang = {de = "German", en = "English", es = "Spanish", fr = "French", it = "Italian", -- Europe
        ja = "Japanese", ko = "Korean", ru = "Russian", zh = "Chinese" -- Asia + Russia
    }
    return ';dictionary\n' .. tableToString(lstLang)
end
function p.translate() -- provides language codes -> localized native names
    local lstLang = {de = "Deutsch", en = "English", es = "Español", fr = "Français", it = "Italiano", -- Latin
        ja = "日本語", ko = "한국어", ru = "Русский", zh = "中文" -- Unicode
    }
    return ';translate\n' .. tableToString(lstLang)
end
return p

In Debug console, validate:

print(p.sequence())
print(p.dictionary())
print(p.translate())

WARNING: Iterator pairs(tab) may iterate in arbitrary order:

;sequence
:table[1] is 10. table[2] is 20. table[3] is 30. 
;dictionary
:table.es is Spanish. table.ja is Japanese. table.fr is French. table.ru is Russian. table.de is German
:table.ko is Korean. table.en is English. table.zh is Chinese. table.it is Italian. 
;translate
:table.es is Español. table.ja is 日本語. table.fr is Français. table.ru is Русский. table.de is Deutsch
:table.ko is 한국어. table.en is English. table.zh is 中文. table.it is Italiano.

Test Your Lua Script

[edit | edit source]

To test your Lua script:

  1. Save the Module:Sandbox to call it from another Wiki page.
  2. Navigate to either the Module_talk:Sandbox page, the Wikiversity:Sandbox page, or your own user or sandbox page.
  3. Add the following code and save the page:
{{#invoke:Sandbox|sequence}}
{{#invoke:Sandbox|dictionary}}
{{#invoke:Sandbox|translate}}

The result should be similar to:

sequence
table[1] is 10. table[2] is 20. table[3] is 30.
dictionary
table.es is Spanish. table.ja is Japanese. table.fr is French. table.ru is Russian. table.de is German
table.ko is Korean. table.en is English. table.zh is Chinese. table.it is Italian.
translate
table.es is Español. table.ja is 日本語. table.fr is Français. table.ru is Русский. table.de is Deutsch
table.ko is 한국어. table.en is English. table.zh is 中文. table.it is Italiano.

Understand Your Lua Script

[edit | edit source]

tableToString

[edit | edit source]

To understand your Lua script tableToString function:

  1. local function tableToString(tab) declares a local function named tableToString that accepts a single parameter tab, which is the table to be converted to a string.
  2. local and the following code defines the variables key, val, and result. All are nil.
  3. The previous lesson is based on string result = ''.
    Let's introduce the table local res = {':'} -- left margin with its counter #res -- length of the table
  4. for key, value in pairs(tab) do creates a loop code block that will vary the value of the variables key and value for each key/value data pair in the table tab.
  5. if tonumber(key) then tests to see if the key can be converted to a number. If it can, the key is displayed as a number (without quotes). If it can't be converted, the key is displayed as a literal string (with quotes).
  6. Compare the string concatenation: result = result .. ':table[' .. key .. '] is ' .. value .. '\n' or
    result = result .. ':table[\'' .. key .. '\'] is ' .. value .. '\n' adds the current key and value to the result.
    res[#res + 1] = 'table[' .. key .. '] is ' .. val .. sep -- [index] will be faster thanks to return table.concat(res).
    • The table[key] notation is a common way to reference individual table keys to access their associated values.
    • To display quotes inside a string, you must either switch between quote identifiers ("/'), or use the \ character to 'escape' the quote, which forces it to be part of the string rather than terminate the string.
  7. end ends the loop.
  8. return table.concat(res) -- concatenation more efficient than string `..` operator returns the concatenation of each item in the table as the result of the function.
  9. end ends the function.

p.sequence

[edit | edit source]

To understand your Lua script sequence function:

  1. function p.sequence() return ';sequence\n' .. tableToString({10, 20, 30}) end -- numerical sequence could be detailed in the following steps.
  2. local numbers = {10, 20, 30} defines a local table variable named numbers, which is initialized with three values.
    When table values are specified without matching keys, Lua automatically adds numeric keys for the values as a sequence from 1 to N, the number of values added. This allows Lua tables to be used similar to how arrays are used in other programming languages. For example, the second value in the table could be referenced as numbers[2], and the table values could be processed with a for loop.
  3. local result defines the variable result and initializes it to nil.
  4. result = ';sequence\n' assigns a literal string value to the variable result. The semi colon is an operator that separates each new statement and the /n means new line.
  5. result = result .. tableToString(numbers) calls the tableToString function, passing the table numbers as the parameter and concatenates the returned value to the variable result.
  6. return result returns the current value of result as the result of the function.
  7. end ends the function.

p.dictionary or p.translate

[edit | edit source]

To understand your Lua script dictionary function:

  1. function p.dictionary() declares a function named dictionary.
  2. local lstLang = {de = "German", en = "English", ... ja = "日本語", ko = "한국어", ... , zh = "中文"} -- Unicode and the following code defines a local table variable named lstLang, which is initialized with 9 key/value pairs.
    • When table values are specified with matching keys, Lua uses the specified keys instead of numeric key values.
    • Lua tables with specified key values cannot be used as arrays using table[number] notation.
    • Lua tables with specified key values can be used as associative arrays using table[key] notation, such as lstLang['ja']. Quotes around string literal keys are required with this notation format.
    • Lua tables with specified key values can also be used as associative arrays using table.key notation, such as lstLang.ja. Quotes around string literal keys are not required with this notation format.
  3. return ';dictionary\n' .. tableToString(lstLang) calls the tableToString function, passing the table lstLang as the parameter and concatenates the returned value as the result of the function.
  4. end ends the function.

It is important to note that the for loop to process table pairs will process all values in the table, but tables with specified key values may not be processed in the order they were created.

Conclusion

[edit | edit source]

Congratulations! You've now created, tested, and understood a Lua script with tables. Continue on to the Errors lesson.

See Also

[edit | edit source]

References

[edit | edit source]
  1. ↑ "Extension:Scribunto/Lua reference manual". Mediawiki. 2026. Retrieved 2026-04-06.