2. Basic Concepts#

本文主要参考自官方文档中的 Basic Concepts 一章.

在开始学习之前, 我们先来看一下怎么 debug lua 脚本. 下面给出了一个例子, 展示了如何在 lua 中写 comment, 以及如何将值打印出来. 打印值将是我们最常用的 debug 方式.

how_to_debug.lua
 1--[[
 2this is multi-line comment
 3line1
 4line2
 5line3
 6]]--
 7
 8-- this is single-line comment
 9a = 1 -- this is single-line comment
10print(a) -- your can print a value to console
11-- you can use string format to print a better message
12print(string.format("a = %s", a))
[1]:
import subprocess

subprocess.run(["lua", "how_to_debug.lua"]);
1
a = 1

2.1 值与类型#

value_and_types_1.lua
 1local a_nil
 2print(string.format("a_nil = %s", a_nil))
 3
 4local a_boolean = true
 5print(string.format("a_boolean = %s", a_boolean))
 6
 7local a_number = 42
 8print(string.format("a_number = %s", a_number))
 9
10local a_string = "Hello World!"
11print(string.format("a_string = %s", a_string))
12
13local a_table = { 1, 2, 3 }
14print(string.format("a_table = %s", a_table))
15
16local a_function = function()
17    print("this is a function!")
18end
19a_function()
[2]:
subprocess.run(["lua", "value_and_types_1.lua"]);
a_nil = nil
a_boolean = true
a_number = 42
a_string = Hello World!
a_table = table: 0x600000c34000
this is a function!

2.2 环境与全局环境#

local_and_global_variable.lua
 1#!/usr/bin/env lua
 2
 3a = 1 -- global variable
 4function func1()
 5    a = 2 -- you can change the value of global variable inside of a function
 6    print(string.format("inside function a = %s", a)) -- should be 2
 7end
 8func1()
 9print(string.format("outside function a = %s", a)) -- should be 2
10
11
12b = 1
13function func2()
14    local b = 2 -- this is NOT the global variable b
15    print(string.format("inside function b = %s", b)) -- should be 2
16end
17func2()
18print(string.format("outside function b = %s", b)) -- should be 1
19
20
21local c = 1
22function func3()
23    c = 2 -- this is the global variable c
24    print(string.format("inside function c = %s", c)) -- should be 2
25end
26func3()
27print(string.format("outside function c = %s", c)) -- should be 2, the local c got overwritten
28
29
30local d = 1
31function func4()
32    local d = 2 -- this is local variable d
33    print(string.format("inside function d = %s", d)) -- should be 2
34end
35func4()
36print(string.format("outside function d = %s", d)) -- should be 1
[3]:
subprocess.run(["lua", "local_and_global_variable.lua"]);
inside function a = 2
outside function a = 2
inside function b = 2
outside function b = 1
inside function c = 2
outside function c = 2
inside function d = 2
outside function d = 1
[ ]: