JavaScript와 Lua의 미묘한 차이점
나는 단순히 JavaScript를 좋아합니다. 너무 우아합니다 (백그라운드에서 한숨을 쉬는 lovestruck fanboy의 조용한 소리를 상상해보십시오).
그래서 최근에는 löve2d 프레임 워크 (nice!) 를 통해 Lua와 게임을했습니다. Lua 도 훌륭하다고 생각합니다. 그들은 내가보기에 두 언어가 매우 비슷합니다.
다음과 같은 명백한 차이점이 있습니다
- 통사론
- 문제 영역
- 도서관
- 유형 (비트)
그러나 어느 것이 더 미묘합니까? Lua에서 약간 다르게 작동하는 JavaScript 코더가 당연한 것으로 생각하는 것이 있습니까? 한 언어의 숙련 된 코더가 다른 언어를 시도하는 데 분명하지 않은 함정이 있습니까?
예를 들어 Lua에서 배열과 해시는 분리되지 않으며 (테이블 만 있음) JavaScript에서는 숫자 배열과 해시 된 개체입니다. 글쎄, 이것은 더 분명한 차이점 중 하나입니다.
그러나 가변 범위, 불변성 또는 이와 비슷한 점이 있습니까?
더 많은 차이점 :
- 루아 는 코 루틴 을 기본적으로 지원합니다 .
- 업데이트 : JS는 이제 생성기 안에 yield 키워드를 포함하여 코 루틴을 지원합니다.
- 루아 는 비교 연산자의 유형을 변환하지 않습니다 . JS에서, 단지
===
와!==
저글링 입력하지 마십시오. - 루아 에는 지수 연산자 (
^
)가 있습니다. JS 는 그렇지 않습니다. JS는 원계 조건 연산자 (포함한 다양한 연산자 사용?:
VS를and/or
5.3 비트 연산자 (현재의)과&
,|
등 대 메타 메소드 ).- 업데이트 : JS는 이제 지수 연산자를 가지고
**
있습니다.
- 업데이트 : JS는 이제 지수 연산자를 가지고
- JS 에는 증가 / 감소, 유형 연산자 (
typeof
및instanceof
), 추가 대입 연산자 및 추가 비교 연산자가 있습니다. - 에서는 JS 는
==
,===
,!=
및!==
운영자가보다 낮은 우선 순위로되어>
,>=
,<
,<=
. Lua에서 모든 비교 연산자는 동일한 우선 순위 입니다. - 루아 는 꼬리 호출을 지원 합니다 .
- 업데이트 : JS는 이제 테일 호출을 지원합니다 .
- Lua 는 변수 목록에 대한 할당을 지원 합니다 . Javascript 에서는 아직 표준이 아니지만 Mozilla의 JS 엔진 (및 Opera의 경우)은 JS 1.7 (Firefox 2의 일부로 제공) 이후 " destructuring assignment " 라는 이름으로 유사한 기능을 지원했습니다 . 함수 정의 및 호출 및 루프 이니셜 라이저 와 같이 할당 이외의 컨텍스트에서 사용할 수 있으므로 JS의 구조 해제가 더 일반적 입니다. Destructuring assignment 는 ECMAScript (Javascript의 언어 표준)에 한동안 제안 된 추가 사항입니다.
- 업데이트 : 디스트 럭처링 (및 디스트 럭처링 할당)은 이제 ECMAScript 사양의 일부입니다. 이미 많은 엔진에 구현되어 있습니다.
- Lua 에서는 연산자 를 오버로드 할 수 있습니다 .
- 에 루아 , 당신과 환경을 조작 할 수 있습니다
getfenv
및setfenv
루아 5.1 또는_ENV
에서 루아 5.2 및 5.3 . - 에서는 JS , 모든 기능은 가변이다. 에 루아 , 기능해야 명시 적으로 가변 인자로 선언 .
Foreach
에 JS 객체 속성 위에 루프. 키워드를 사용하는 Lua의 Foreach 는 반복자를 반복하며보다 일반적입니다.for
- 업데이트 : JS에는 Iterables 도 있습니다. 많은 것들이 당신이 기대하는 일반적인 데이터 구조에 내장되어
Array
있습니다. 이것들은for...of
구문 으로 반복 될 수 있습니다 . 일반 객체의 경우 자체 반복자 함수를 구현할 수 있습니다. 이것은 루아에 훨씬 가깝습니다.
- 업데이트 : JS에는 Iterables 도 있습니다. 많은 것들이 당신이 기대하는 일반적인 데이터 구조에 내장되어
JS에는 전역 및 기능 범위가 있습니다. Lua 는 글로벌 및 블록 범위를 가지고 있습니다. 제어 구조 (예를 들면
if
,for
,while
) 신규 도입 블록을 .범위 지정 규칙의 차이로 인해 외부 변수에 대한 클로저의 참조 (Lua 어법에서 "upvalues"라고 함)는 Lua와 Javascript 에서 다르게 처리 될 수 있습니다 . 이것은 루프 에서 클로저로
for
가장 일반적으로 발생하며 놀랍게도 일부 사람들을 잡습니다. 에서는 자바 하는 본문for
모든 기능의 모든 기준을 루프 본체에서 선언 있도록 루프는 새로운 범위를 도입하지 않는 동일한 외부 변수 . Lua에서for
루프를 반복 할 때마다 루프 변수마다 새로운 로컬 변수가 생성됩니다.local i='foo' for i=1,10 do -- "i" here is not the local "i" declared above ... end print(i) -- prints 'foo'
위 코드는 다음과 같습니다.
local i='foo' do local _i=1 while _i<10 do local i=_i ... _i=_i+1 end end print(i)
As a consequence, functions defined in separate iterations have different upvalues for each referenced loop variable. See also Nicolas Bola's answers to Implementation of closures in Lua? and "What are the correct semantics of a closure over a loop variable?", and "The Semantics of the Generic for".
UPDATE: JS has block scope now. Variables defined with
let
orconst
respect block scope.
- Integer literals in JS can be in octal.
- JS has explicit Unicode support, and internally strings are encoded in UTF-16 (so they are sequences of pairs of bytes). Various built-in JavaScript functions use Unicode data, such as
"pâté".toUpperCase()
("PÂTÉ"
). Lua 5.3 and up have Unicode code point escape sequences in string literals (with the same syntax as JavaScript code point escape sequences) as well as the built-inutf8
library, which provides basic support for the UTF-8 encoding (such as encoding code points into UTF-8 and decoding UTF-8 into code points, getting the number of code points in a string, and iterating over code points). Strings in Lua are sequences of individual bytes and can contain text in any encoding or arbitrary binary data. Lua does not have any built-in functions that use Unicode data; the behavior ofstring.upper
depends on the C locale. - In Lua, the
not
,or
,and
keywords are used in place of JS's!
,||
,&&
. - Lua uses
~=
for "not equal", whereas JS uses!==
. For example,if foo ~= 20 then ... end
. - Lua 5.3 and up use
~
for binary bitwise XOR, whereas JS uses^
. - In Lua, any type of value (except
nil
andNaN
) can be used to index a table. In JavaScript, all non-string types (except Symbol) are converted to strings before being used to index an object. For example, after evaluation of the following code, the value ofobj[1]
will be"string one"
in JavaScript, but"number one"
in Lua:obj = {}; obj[1] = "number one"; obj["1"] = "string one";
. - In JS, assignments are treated as expressions, but in Lua they are not. Thus, JS allows assignments in conditions of
if
,while
, anddo while
statements, but Lua does not inif
,while
, andrepeat until
statements. For example,if (x = 'a') {}
is valid JS, butif x = 'a' do end
is invalid Lua. - Lua has syntactic sugar for declaring block-scoped function variables, functions that are fields, and methods (
local function() end
,function t.fieldname() end
,function t:methodname() end
). JS declares these with an equals sign (let funcname = function optionalFuncname() {}
,objectname.fieldname = function () {}
).
A couple of subtle differences that will catch you out at least once:
- Not equal is spelled
~=
in Lua. In JS it is!=
- Lua arrays are 1-based - their first index is 1 rather than 0.
- Lua requires a colon rather than a period to call object methods. You write
a:foo()
instead ofa.foo()
†
† you can use a period if you want, but have to pass the self
variable explicitly. a.foo(a)
looks a bit cumbersome. See Programming in Lua for details.
To be honest it would be easier to list the things which are common to Javascript and Lua than to list the differences. They are both dynamically-typed scripting languages, but that's about as far as you can go really. They have totally different syntax, different original design goals, different modes of operation (Lua is always compiled to bytecode and run on the Lua VM, Javascript varies), the list goes on and on.
JavaScript arrays and objects are closer than you might think. You can use array notation to get at the elements of either of them, and you can add non-numeric indices to arrays. Individual array elements can hold anything, and the array can be sparse. They are nearly identical cousins.
Off the top of my head
Lua ...
- supports coroutines
- has no restriction to just string/number as key for a table. Everything works.
- the error handling is somewhat clumsy. Either you don't handle anything or use the pcall method
- I think I read something about differences in the lexical scope and that Lua has the better one.
- If I recall correctly regular expression support in lua is limited
I liked this question and the answers provided. Additional reasons the two languages seem more alike than not to me:
Both assign functions to variables, can build functions on the fly, and define closures.
A test reveals that current Javascript also returns objects, or at least strings from logic expressions like lua does:
function nix(){
alert(arguments[0]||"0");
}
nix();
Lua and JavaScript are both prototype base languages.
참고URL : https://stackoverflow.com/questions/1022560/subtle-differences-between-javascript-and-lua
'Programing' 카테고리의 다른 글
.NET에서 특정 앱의 여러 인스턴스를 방지합니까? (0) | 2020.07.14 |
---|---|
파라미터로 메소드를 문서화하는 방법은 무엇입니까? (0) | 2020.07.14 |
배쉬 : 구문 오류 : 예기치 않은 리디렉션 (0) | 2020.07.14 |
ScalaTest와 Scala Specs 단위 테스트 프레임 워크의 차이점은 무엇입니까? (0) | 2020.07.14 |
Eclipse : 동일한 편집기 탭을 사용하여 여러 번 검색 한 파일 (0) | 2020.07.14 |