Lua/Tables

From Wikiversity
< Lua
Jump to navigation Jump to search

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.

Create a Lua Script with Tables[edit | edit source]

To create a Lua script with tables:

  1. Navigate to Module:Sandbox.
  2. Clear all existing code.
    It's a sandbox. Everyone is free to play in the sandbox. But if you find another user is actively editing the sandbox at the same time, you may also use Module:Sandbox/Username, where Username is your Wikiversity username.
  3. Add the following code and save the page:
local p = {}
 
local function tableToString(t)
    local key
    local value
    local result
 
    result = ''
 
    for key, value in pairs(t) do
        if (tonumber(key) ~= nil) then
            result = result .. ':table[' .. key .. '] is ' .. value .. '\n'
        else
            result = result .. ':table[\'' .. key .. '\'] is ' .. value .. '\n'
        end
    end
 
    return result
end
 
function p.sequence()
    local numbers = {10, 20, 30}
    local result
 
    result = ';sequence\n'
    result = result .. tableToString(numbers)
 
    return result
end
 
function p.dictionary()
    local languages = {
        ['de'] = 'German',
        ['en'] = 'English',
        ['es'] = 'Spanish',
        ['fr'] = 'French',
        ['it'] = 'Italian',
        ['ja'] = 'Japanese',
        ['ko'] = 'Korean',
        ['ru'] = 'Russian',
        ['zh'] = 'Chinese'
    }
    local result
 
    result = ';dictionary\n'
    result = result .. tableToString(languages)
 
    return result
end
 
return p

Test Your Lua Script[edit | edit source]

To test your Lua script:

  1. Navigate to either the Module_talk:Sandbox page, the Wikiversity:Sandbox page, or your own user or sandbox page.
  2. Add the following code and save the page:
{{#invoke:Sandbox|sequence}}
{{#invoke:Sandbox|dictionary}}

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

Understand Your Lua Script[edit | edit source]

To understand your Lua script tableToString function:

  1. local function tableToString(t) declares a local function named tableToString that accepts a single parameter t, which is the table to be converted to a string.
  2. local and the following code defines the variables key, value, and result. All are nil.
  3. result = '' assigns an empty string literal value to the variable result.
  4. for key, value in pairs(t) 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 t.
  5. if (tonumber(key) ~= nil) 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. result = result .. ':table[' .. key .. '] is ' .. value .. '\n' or result = result .. ':table[\'' .. key .. '\'] is ' .. value .. '\n' adds the current key and value to the result.
    • 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 result returns the current value of result as the result of the function.
  9. end ends the function.

To understand your Lua script sequence function:

  1. function p.sequence() declares a function named sequence.
  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.

To understand your Lua script dictionary function:

  1. function p.dictionary() declares a function named dictionary.
  2. local languages = { and the following code defines a local table variable named languages, 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 languages['en']. 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 languages.en. Quotes around string literal keys are not required with this notation format.
  3. local result defines the variable result and initializes it to nil.
  4. result = ';dictionary\n' assigns a literal string value to the variable result.
  5. result = result .. tableToString(languages) calls the tableToString function, passing the table languages 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.

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]