e-Lua: basics and datatypes


The basics of Lua language using NodeMcu interpreter.

This are just my notes on NodeMcu's Lua. If you want to go further on the subject:

http://www.lua.org/

http://lua-users.org/wiki/LuaDirectory , specially http://lua-users.org/wiki/TutorialDirectory . I use this one extensively.

http://www.eluaproject.net/

To play with Lua (in you PC, not in NodeMcu) I strongly recommend ZeroBrane Studio.

All the examples of my e-Lua chapters are tested (results copied and pasted) using ESPlorer and a Wemos D1 board with a "float" firmware.

Comments

-- Two dashes start a one-line comment.

--[[
     Adding two ['s and ]'s makes it a
     multi-line comment.
--]]

Case, whitespaces, linebreaks and separators

In Lua, case is relevant: "House" is not the same as "house".

Lua ignores whitespaces and line breaks.

Lua does not need a separator between two consecutive statements, but you can use a semi-colon if you wish.

Assign and print()

Assigning is done using the equal sign = and print() is the classic print function.

> x= 3
> print (x)
3

I find that to get a result in the console you can use = instead of print. I'm not sure what's the syntax behind that.

> a= 12
> b= "house"
> =a
12
> =b
house

Global and local variables

Variables in Lua are always global, unless specified otherwise with the command local.

Datatypes

To know the datatype of an object, you can use the function type() :

> a=33
> =type(a)
number
> a="hello"
> =type(a)
string
nil

Not the same as zero or false. It is a "nonexistent". If you assign nil to a variable, the variable ceases to exist. If you try to access something that does not exist, you get nil as return.

> print(z)
nil
> a= 12
> a= nil
> print(a)
nil
Numbers

Lua assumes all numbers as float, but I presume if you flash your NodeMcu with a "integer" firmware that will not be true.

> print (7 + 2)
9
> print (7 / 2)
3.5
Strings

You create strings enclosing them with quotes or double quotes.

> print ("my string")
my string
> print ('my string')
my string

Strings can be concatenated using the operator ..

> a= "my "
> b= "house is "
> c= 10
> print(a..b..c)
my house is 10
Boolean

true and false, like most languages.

> x = 3 > 2
> print (x)
true
> x = 3 < 2
> print (x)
false
Tables

Tables are so important and have so many features that i made a chapter for them.

Functions

They also have their own chapter.

Userdata

Userdata values are objects foreign to Lua, such as objects implemented in C. I don't think I will be using this so soon.

Thread

A thread value represents an independent (cooperative) thread of execution. I'll leave this one for later too.

results matching ""

    No results matching ""