We use cookies on this site to enhance your user experience

Assignment Statements

Assignment Statements

Aug 29 2019, 9:28 AM PST 2 min

The assignment statement is used to assign a value to a variable. Assignment is used in many things such as variable and property assignments.

For example, the following code would set the Anchored property for the part named “Part” to false:

Workspace.Part.Anchored = false
myVariable = 1337


There are notionally three types of assignment:

  • To scoped variables (declared as local)
  • To table keys
    • If the table has a metatable, look at local newindex ## rawget(debug.getmetatable(t), **__newindex**). If it is a function, invoke that as newindex(t, key, value). If it is a table, instead run newindex[key] value
    • To environment (typically global) variables
  • Environment variable assignments are actually a special case of 2 - they use the table returned by getfenv()

Here’s some code that marks out each type:

local a = "Hello World" -- scoped
local b = {}            -- scoped
a = "Goodbye world"     -- scoped

c = {}                  -- environment

function foo(arg)       -- environment - declaring a function assigns it to a global variable
    -- ...

local function bar(arg) -- scoped - unless you precede it with a local keyword
    -- ...
function a(arg)         -- scoped - or you use a name already declared as local
    arg = arg + 1       -- scoped - parameters are treated as local variables

b.key = 1               -- table
c.key = 1               -- table - it doesn't matter whether the table is in a global variable

function c.func(arg)    -- table
    -- ...
function c:method(arg)  -- table
    -- ...
  • lua
  • coding
  • concept