English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Variáveis do Lua

变量在使用前,需要在代码中进行声明,即创建该变量。

编译程序执行代码之前编译器需要知道如何给语句变量开辟存储区,用于存储变量的值。

Lua 变量有三种类型:全局变量、局部变量、表中的域。

Lua 中的变量全是全局变量,那怕是语句块或是函数里,除非用 local 显式声明为局部变量。

局部变量的作用域为从声明位置开始到所在语句块结束。

变量的默认值均为 nil。

-- test.lua 文件脚本
a = 5               -- 全局变量
local b = 5         -- 局部变量
function joke()
    c = 5           -- 全局变量
    local d = 6     -- 局部变量
end
joke()
print(c,d)          --> 5 nil
do 
    local a = 6     -- 局部变量
    b = 6           -- 对局部变量重新赋值
    print(a,b);     --> 6 6
end
print(a, b)      --> 5 6

执行以上示例输出结果为:

$ lua test.lua 
5    nil
6    6
5    6

赋值语句

赋值是改变一个变量的值和改变表域的最基本的方法。

a = "hello" .. "world"
t.n = t.n + 1

Lua 可以对多个变量同时赋值,变量列表和值列表的各个元素用逗号分开,赋值语句右边的值会依次赋给左边的变量。

a, b = 10, 2*x       <-->       a=10; b =2*x

Quando encontra uma instrução de atribuição, o Lua calcula todos os valores da direita antes de executar a operação de atribuição, portanto, podemos fazer a troca de valores das variáveis dessa forma:

x, y = y, x                     -- swap 'x' for 'y'
a[i], a[j] = a[j], a[i]         -- swap 'a[i]' for 'a[j]'

When the number of variables and the number of values are not the same, Lua will take the following strategies based on the number of variables:

a. The number of variables > The number of values             Fill with nil according to the number of variables
b. The number of variables < The number of values             Excess values will be ignored
a, b, c = 0, 1
print(a, b, c)             --> 0   1   nil
 
a, b = a+1, b+1, b+2     -- value of b+2 is ignored
print(a, b)               --> 1   2
 
a, b, c = 0
print(a, b, c)             --> 0   nil   nil

O último exemplo é uma situação de erro comum, observe: se você quiser atribuir a múltiplas variáveis, é necessário atribuir a cada uma delas em ordem.

a, b, c = 0, 0, 0
print(a, b, c)             --> 0   0   0

A atribuição de múltiplos valores é frequentemente usada para trocar variáveis ou atribuir valores de retorno de funções a variáveis:

a, b = f()

f() retorna dois valores, o primeiro atribuído a a, o segundo a b.

Deve-se usar variáveis locais o mais possível, pois há dois benefícios:

  • 1. Evite conflitos de nomes.

  • 2. Acesso a variáveis locais é mais rápido do que às variáveis globais.

Índice

Use colchetes [] para acessar índices da table. O Lua também oferece a operação .

t[i]
t.i                 -- Escreva uma forma abreviada quando o índice é do tipo string
gettable_event(t,i) -- Acesso por índice é essencialmente uma chamada de função semelhante a esta
> site = {}
> site["key"] = "pt.oldtoolbag.com"
> print(site["key"])
pt.oldtoolbag.com
> print(site.key)
pt.oldtoolbag.com