- 黄金
- 192.55G
1.变量声明和使用:
2.条件语句(if-else):
3.循环语句(for):
4.表(Table)声明和访问:
5.函数声明和调用:
6.对象(Table)声明和访问:
7.模块导入和使用:
8.异常处理:
Lua:
name = "John"
age = 25
print("My name is " .. name .. " and I am " .. age .. " years old.")
2.条件语句(if-else):
Lua:
score = 85
if score >= 60 then
print("You passed the exam!")
else
print("You failed the exam.")
end
3.循环语句(for):
Lua:
for i = 1, 5 do
print("Number: " .. i)
end
4.表(Table)声明和访问:
Lua:
fruits = {"apple", "banana", "orange"}
print(fruits[1]) -- 输出 "apple"
5.函数声明和调用:
Lua:
function greet(name)
print("Hello, " .. name .. "!")
end
greet("Alice") -- 输出 "Hello, Alice!"
6.对象(Table)声明和访问:
Lua:
person = {
name = "John",
age = 30,
greet = function()
print("Hello, my name is " .. person.name .. "!")
end
}
print(person.name) -- 输出 "John"
print(person.age) -- 输出 30
person.greet() -- 输出 "Hello, my name is John!"
7.模块导入和使用:
Lua:
-- 文件1.lua
module = {}
module.variable = "Hello from file 1!"
return module
-- 文件2.lua
local module = require("1")
print(module.variable) -- 输出 "Hello from file 1!"
8.异常处理:
Lua:
function divide(numerator, denominator)
if denominator == 0 then
error("Division by zero error!")
end
return numerator / denominator
end
success, result = pcall(divide, 10, 0)
if success then
print(result)
else
print("Error: " .. result)
end
最后编辑: