我是Lua初学者【2】

这篇博客介绍了Lua的语法,包括if else的使用,Table的内存管理,以及Function的不定参数应用。特别强调了Table的引用计数特性,当没有变量引用Table时,Lua会自动释放内存。此外,还展示了如何利用Table和Function将Lua用于数据描述,类似于XML,并解释了函数调用和返回值的栈操作原理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

SYNTAX

1、if else用法比较简单, 类似于C语言, 不过此处需要注意的是整个if只需要一个end,
哪怕用了多个elseif, 也是一个end.
例如
  if op == "+" then
    r = a + b
  elseif op == "-" then
    r = a - b
  elseif op == "*" then
    r = a*b
  elseif op == "/" then
    r = a/b
  else
    error("invalid operation")
  end

SYSTEM

1、Lua对Table占用内存的处理是自动的, 如下面这段代码
  a = {}
  a["x"] = 10
  b = a     -- `b' refers to the same table as `a'
  print(b["x"]) --> 10
  b["x"] = 20
  print(a["x"]) --> 20
  a = nil   -- now only `b' still refers to the table
  b = nil   -- now there are no references left to the table
b和a都指向相同的table, 只占用一块内存, 当执行到a = nil时, b仍然指向table,
而当执行到b=nil时, 因为没有指向table的变量了, 所以Lua会自动释放table所占内存

FUNCTION

1、不定参数
-- Functions can take a
-- variable number of
-- arguments.
function funky_print (...)  
for i=1, arg.n do      
print("FuNkY: " .. arg)  
end
end

funky_print("one", "two")

运行结果
FuNkY: one
FuNkY: two

程序说明
* 如果以...为参数, 则表示参数的数量不定.
* 参数将会自动存储到一个叫arg的table中.
* arg为local变量,在一个function内
* arg.n中存放参数的个数. arg[]加下标就可以遍历所有的参数.

2、把Lua变成类似XML的数据描述语言

function contact(t)  
-- add the contact ‘t’, which is  
-- stored as a table, to a database
end

contact {  
name = "64bit baboosh",  
email = "asdic.xxs@gmail.com",
url = http://blog.youkuaiyun.com/tcxxs,  
quote = [[      
There are
10 types of people    
who can understand binary.]]
}

contact {  
-- some other contact
}

程序说明
* 把function和table结合, 可以使Lua成为一种类似XML的数据描述语言
* e09中contact{...}, 是一种函数的调用方法, 不要弄混了
* [[...]]是表示多行字符串的方法
* 当使用C API时此种方式的优势更明显, 其中contact{..}部分可以另外存成一配置文件

3、Lua的函数可以有多个参数, 也可以有多个返回值, 这都是由栈(stack)实现的.
需要调用一个函数时, 就把这个函数压入栈, 然后顺序压入所有参数, 然后用
lua_call()调用这个函数. 函数返回后, 返回值也是存放在栈中. 这个过程和
汇编执行函数调用的过程是一样的.

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值