Lua 基本语法
Lua 基本语法
Lua 是一种轻量级、高效的脚本语言,主要用于嵌入式系统开发、游戏开发、图形图像处理等领域。Lua 具有简单易用、可扩展、高性能等特点,是当前最流行的脚本语言之一。
注释
- 单行注释:以
--
开头,注释内容直到行末停止。 - 多行注释:以
--[[
开头,以]]
结尾,包裹注释内容。
-- This is a single line comment
--[[
This is a
multi-line
comment
--]]
数据类型
Lua 是动态类型语言,变量不需要先声明类型。Lua 中的数据类型包括:
- nil:空值,无数据。
- boolean:true 和 false。
- number:表示实数,包括整数和浮点数。
- string:字符串,由一系列字符组成。
- function:函数,可以作为参数和返回值。
- table:表,用于存储和操作数据。
- userdata:表示 C 语言中的类型,用于扩展 Lua。
变量
Lua 使用 $
符号来表示变量,变量名是以字母或下划线开头的字符序列。Lua 中的变量可以存储任意数据类型。
-- Assigning values to variables
local x = 10
local y = "hello world"
-- Outputting values
print(x) -- Output: 10
print(y) -- Output: hello world
控制流
Lua 支持常见的控制流语句,如 if、for、while、repeat-until、break、return 等。
-- if-elseif-else statement
local x = 10
if x < 0 then
print("x is negative")
elseif x > 0 then
print("x is positive")
else
print("x is zero")
end
-- for loop
for i = 1, 10, 1 do
print(i)
end
-- while loop
local i = 1
while i <= 10 do
print(i)
i = i + 1
end
-- repeat-until loop
local j = 1
repeat
print(j)
j = j + 1
until j > 10
函数
Lua 中的函数使用关键字 function
定义,有多个参数时使用逗号分隔。函数可以有多个返回值,使用逗号分隔。
-- Define a function that takes two arguments and returns their sum
function add(x, y)
return x + y
end
-- Call the function and output the result
local result = add(10, 20)
print(result) -- Output: 30
表
Lua 中的表是一种灵活的数据结构,可以存储任意类型的数据。表可以包含其他表,也可以作为其他表的值和键。
-- Define a table with string keys
local myTable = {}
myTable["name"] = "John"
myTable["age"] = 30
-- Define a table with numeric keys
local myOtherTable = {10, 20, 30}
-- Access the values of the tables
print(myTable["name"]) -- Output: John
print(myOtherTable[2]) -- Output: 20
模块
Lua 中的模块是一种封装数据和代码的方法,可以在不同的文件之间共享代码和数据。Lua 模块命名方式使用 .
表示多级命名。
-- Define a module
local myModule = {}
function myModule.add(x, y)
return x + y
end
function myModule.subtract(x, y)
return x - y
end
return myModule
-- Access the module in another file
local myModule = require("myModule")
local result = myModule.add(10, 20)
print(result) -- Output: 30
结论
本文介绍了 Lua 基本语法,包括注释、数据类型、变量、控制流、函数、表和模块。学习 Lua 基本语法是使用 Lua 的第一步,为进一步深入学习和应用 Lua 打下基础。