Форумчанин
Регистрация: 01.05.2018
Сообщений: 104
|
Цитата:
Сообщение от p51x
Я вот сразу поставлю минус. Нет, это вы скопировали не с сайта луа, а с другого, где рассказывают про отличия луа от других скриптовых. Ну и т.д.
|
https://www.luafaq.org/gotchas.html
Цитата:
Lua Gotchas
1 Calling methods
2 Values which are false
3 Undeclared variables
3.1 .. are global by default
3.2 Variables must be declared before use.
4 All numbers are floating point
5 When does automatic conversion to string occur?
6 Tables are both arrays and dictionaries
6.1 Arrays start at one
6.2 Table keys
6.3 Undefined field access is a feature
6.4 Arrays with holes are bad news
6.5 Element order with pairs() is arbitrary
7 When to use parentheses with functions?
8 Expressions with multiple values
8.1 Functions can return multiple values
8.2 A Superficial similarity with Python
8.3 Multiple Assignments in Declarations
9 Values and references
10 Using metatables
10.1 __index is a fallback
10.2 __index can be a table
10.3 __eq cannot be used to compare arbitrary values
'Gotchas' are Lua features which are often confusing at first, if you are used to other languages.
Here is a short list compiled from the Lua mailing list, particularly by Timothy Hunter.
1 Calling methods
If you are used to other languages, then obj.method() looks like a method call, but really it is just looking up 'method' in the context of obj and then calling that function. To make a proper method call, use obj:method() which is 'syntactical sugar' for obj.method(obj) - that is, the colon passes the object as the first argument as self. Common methods encountered in basic Lua programming are the string methods, like s:find("hello") being short for string.find(s,"hello").
2 Values which are false
C-like languages regard 0 as equivalent to false, but this is not true for Lua. Only an explicit false or nil are equivalent to false. When in doubt, make the condition explicit, e.g. if val == nil then ... end unless the value is actually boolean.
3 Undeclared variables
3.1 .. are global by default
Like all dynamic languages, you don't have to declare variables. However, the scope of what gets implicitly declared is not the same. For instance, an undeclared variable is local to the function in Python, and you need the keyword global to tell the interpreter to look outside. In Lua, the situation is exactly opposite; unless declared using local, Lua will look up a name in the current environment, which is usually _G.
Also, the value of an undeclared variable is nil, because there is no special undefined value. Since nil may be an acceptable value for a variable, typing errors can bite deep.
In larger programs, this can lead to madness, so people often use a technique which traps undefined global access - see strict model.
3.2 Variables must be declared before use.
This might seem an obvious point, but in JavaScript function declarations are 'hoisted' so that they can be declared in any order. This also works in Python:
def foo():
def bar ():
zog()
def zog():
print "Zog!"
bar()
but the equivalent Lua does not because zog has not yet been declared:
function foo()
local function bar() zog() end
local function zog() print "Zog!" end
bar()
end
4 All numbers are floating point
The good news is that any integer up to 2^52 can be represented exactly by a 64-bit double-precision value. But don't expect equality to work always for floating-point values! (This is more a general programming gotcha, since you must become used to finite precision.)
Lua can be compiled only to use integer arithmetic on embedded platforms that lack hardware floating-point support.
5 When does automatic conversion to string occur?
10+"20" does work in Lua, but 10=="10" is not true. In an arithmetic expression, Lua will attempt to convert strings to numbers, otherwise you will get a 'attempt to perform arithmetic on a string value'. Fortunately, string concatenation is a separate operator, so JavaScript-style weirdness does not happen so often: "10".."20" is unambiguously "1020".
6 Tables are both arrays and dictionaries
Lua tables are the ultimate one-stop-shop of data structures. It can be confusing that a table can behave like both kinds of containers at once, such as {1,2,3,enable=true}. So you will see reference to the array-part and the 'hash' part of a table.
6.1 Arrays start at one
This gets people because starting at zero is more common, and the habit is hard to break. The problem is that t[0] = 1 is not considered a problem, but then the length of the array will be off-by-one. The value is in the table, but is in the 'hash' or 'dictionary' part. The length operator # only applies from 1 to the last non-nil element.
6.2 Table keys
The 'key' in t.key is a constant 'key', not the variable named 'key'. This is because t.key is the same as t["key"]. If you want to index by a variable, say t[key]. This 'quoting' also happens in table constructors, e.g. t={key=1} sets the value of t.key. But, this can only work for valid Lua names that aren't keywords or contain special characters. So you must say t={["for"]=1,...}' andt["for"]`.
JavaScript programmers will be comfortable with Lua tables, but remember there is no distinction between 'undefined' and 'null'.
6.3 Undefined field access is a feature
In many languages, trying to access a non-existent key in a list or dictionary causes an exception; in Lua the result is simply nil. This is unambiguous because nil cannot be usefully put into tables.
6.4 Arrays with holes are bad news
Try not to put nil in arrays. It will work if you know what you're doing, but the length operator # will be confused and standard table functions like table.sort() will complain bitterly.
Sparse arrays have their uses, if you remember not to depend on #:
> t = {}
> t[1] = 1
> t[4] = 4
> t[10] = 10
> = #t --> NB!
1
> for k,v in pairs(t) do print(k,v) end
1 1
4 4
10 10
6.5 Element order with pairs() is arbitrary
Yes, you can use pairs() with an 'array', but don't expect to get the keys in ascending order. That is the first reason for ipairs() which makes that guarantee. The second reason for ipairs() is that it only goes over the 'array' part of a table.
7 When to use parentheses with functions?
|
|