Форум программистов
 
Контакты: о проблемах с регистрацией, почтой и по другим вопросам пишите сюда - alarforum@yandex.ru, проверяйте папку спам! Обязательно пройдите активизацию e-mail.

Вернуться   Форум программистов > Клуб программистов > Свободное общение
Регистрация

Восстановить пароль
Повторная активизация e-mail


Донат для форума - использовать для поднятия настроения себе и модераторам

А ещё здесь можно купить рекламу за 25 тыс руб в месяц! ) пишите сюда - alarforum@yandex.ru

Ответ
 
Опции темы
Старый 16.08.2019, 22:46   #1
Haberman
Форумчанин
 
Регистрация: 01.05.2018
Сообщений: 103
Репутация: -10
По умолчанию зашел на сайт Lua, почитать про язык Lua а они там про Питонов расказывают

Неверите? вот
Цитата:
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
Питоны везде! Наползают..
Haberman вне форума   Ответить с цитированием
Старый 16.08.2019, 23:10   #2
p51x
Профессионал
 
Регистрация: 15.02.2010
Сообщений: 14,701
Репутация: 2631
По умолчанию

Я вот сразу поставлю минус. Нет, это вы скопировали не с сайта луа, а с другого, где рассказывают про отличия луа от других скриптовых. Ну и т.д.
__________________
Запомните раз и навсегда: помочь != "решите за меня"!
p51x вне форума   Ответить с цитированием
Старый 19.08.2019, 18:46   #3
Haberman
Форумчанин
 
Регистрация: 01.05.2018
Сообщений: 103
Репутация: -10
По умолчанию

Цитата:
Сообщение от 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?
Haberman вне форума   Ответить с цитированием
Старый 19.08.2019, 18:57   #4
p51x
Профессионал
 
Регистрация: 15.02.2010
Сообщений: 14,701
Репутация: 2631
По умолчанию

Еще раз:
https://www.luafaq.org/
Цитата:
Lua Unofficial FAQ (uFAQ)
Там даже логотип намекает. Зря нельзя еще раз минус поставить...
__________________
Запомните раз и навсегда: помочь != "решите за меня"!
p51x вне форума   Ответить с цитированием
Старый 19.08.2019, 19:10   #5
Haberman
Форумчанин
 
Регистрация: 01.05.2018
Сообщений: 103
Репутация: -10
По умолчанию

Цитата:
Сообщение от p51x Посмотреть сообщение
https://www.luafaq.org/

Там даже логотип намекает. ..
Подстава, что еще сказать.
Haberman вне форума   Ответить с цитированием
Ответ

Опции темы

Ваши права в разделе
Вы не можете создавать новые темы
Вы не можете отвечать в темах
Вы не можете прикреплять вложения
Вы не можете редактировать свои сообщения

BB коды Вкл.
Смайлы Вкл.
[IMG] код Вкл.
HTML код Выкл.

Быстрый переход

Похожие темы
Тема Автор Раздел Ответов Последнее сообщение
Какой язык программирования нужно выучить , чтобы создать сайт ? Smith0117 Общие вопросы по программированию, компьютерным наукам 1 03.01.2018 01:38
И тут я зашел в интерфейс IEnumerable BadCats C# (си шарп) 2 31.08.2016 15:57
последний зашел, первый вышел RusikOk Общие вопросы C/C++ 6 05.11.2014 21:22
Определить, человек зашел на страницу или робот. Mr_freeman PHP 5 27.09.2013 18:26
Зашел поздороваться (после Армии) Neymexa Свободное общение 21 05.08.2011 17:39


12:25.


Powered by vBulletin® Version 3.8.11
Copyright ©2000 - 2019, Jelsoft Enterprises Ltd.