关于lua table.getn()和#
2016-06-13 14:47
741 查看
在lua中table是强大的数据组合类型,但是因为强大所以有些地方使用会不好理解。
table可以是list:
table可以是dict:
table可以是链表:
当然table也可以混合。
lua5.0之后版本
但是有个问题是在获取table的长度的时候:
2.5.5 - The Length Operator
The length operator is denoted by the unary operator #. The length of a string is its number of bytes (that is, the usual meaning of string length when each character is one byte).
The length of a table t is defined to be any integer index n such that t
is not nil and t[n+1] is nil; moreover, if t[1] is nil, n can be zero. For a regular array, with non-nil values from 1 to a given n, its length is exactly that n, the index of its last value. If the array has “holes” (that is, nil values between other non-nil values), then #t can be any of the indices that directly precedes a nil value (that is, it may consider any such nil value as the end of the array).
所以在有需要获取长度的table中尽量不要使用混合table,并且不要设置nil。如果你设置nil,你需要手动去修改table的长度
虽然我们可以通过设置某个元素为
如果想避免遇到莫名的麻烦,尽量让你的table更简单。
table可以是list:
local list_table = {1, 2, 3}
table可以是dict:
local dict_table = {a=1,b=2}
table可以是链表:
local lb_tale={value = 1, next=nil}
当然table也可以混合。
lua5.0之后版本
table.getn()被废弃,可使用
#.
但是有个问题是在获取table的长度的时候:
2.5.5 - The Length Operator
The length operator is denoted by the unary operator #. The length of a string is its number of bytes (that is, the usual meaning of string length when each character is one byte).
The length of a table t is defined to be any integer index n such that t
is not nil and t[n+1] is nil; moreover, if t[1] is nil, n can be zero. For a regular array, with non-nil values from 1 to a given n, its length is exactly that n, the index of its last value. If the array has “holes” (that is, nil values between other non-nil values), then #t can be any of the indices that directly precedes a nil value (that is, it may consider any such nil value as the end of the array).
所以在有需要获取长度的table中尽量不要使用混合table,并且不要设置nil。如果你设置nil,你需要手动去修改table的长度
table.setn()
虽然我们可以通过设置某个元素为
nil来达到删除这个元素的目的,但是直接进行设置会带来获取长度的问题,可以使用
table.remove(index)来删除,但是这个方法还是有很多局限的。
如果想避免遇到莫名的麻烦,尽量让你的table更简单。
相关文章推荐
- 详解Lua中的表的概念及其相关操作方法
- Lua编程示例(二):面向对象、metatable对表进行扩展
- 把Lua编译进nginx步骤方法
- Lua脚本自动生成APK包
- Lua中的元表(metatable)、元方法(metamethod)详解
- Lua中的metatable介绍
- Lua中ipair和pair的区别
- Lua中的函数精讲笔记
- 浅谈Lua的面向对象特性
- 详解Lua中的变量相关知识点
- Lua脚本语言入门笔记
- Lua脚本调用外部脚本
- 详解Lua中的if语句的使用方法
- Lua中调用函数使用点号和冒号的区别
- Lua中的闭合函数、非全局函数与函数的尾调用详解
- Lua中强大的元方法__index详解
- Lua中调用C++函数示例
- Lua面向对象之类和继承浅析
- Lua性能优化技巧(一):前言
- Lua中获取table长度问题探讨