Working with Lua on an ESP8266

TLDR; use luatool to upload scripts Lua is a scripting language which has been ported to the ESP8266. After flashing the latest firmware you can connect to the module using

screen /dev/ttyUSB0

You probably want to save your entered code over a restart. Nodemcu offers a whole file api which tells you how to manipulate the virtual filesystem. file api use this example to write into a file


file.open("init.lua", "w+")
file.writeline('foo bar')
file.close()

you can also continue writing to a file with


file.open("init.lua", "w+")
file.writeline('foo bar')
file.close()

to read the file use

file.open("init.lua", "r")
print(file.read('\r'))
file.close()

remove the file with

file.remove("init.lua")

luatool.py A better way is to write files locally on your computer, then upload and execute those files on the module. You can do so by installing luatool. Afterwards you write your files in one folder and change into it. Execute this code // UNTESTED

for file in *.lua; do
      luatool.py --port /dev/ttyUSB0 --src $file --dest $file --verbose;
done &&
luatool.py --port /dev/ttyUSB0 -r

This uploads your *.lua files and restarts the module to test the code. making luatool.py more tolerant to errors Uploads frequently fail because of different line endings in Linux, Windows and Mac. I changed luatool.py to accept nearly all combinations by changing the line 48 from

if line+'\r' == data:

to

if line+'\r' == data or line+'\n' == data or line+'\n'+'\r' == data or line+'\r'+'\n' == data or line == data:

Writing Code The file init.lua is executed in startup. I use init.lua as an init script where I register my different modules (i.e. files). Edit init.lua like this

dofile("main.lua")
dofile("wifi.lua")
dofile("httpserver.lua")

Leave Comment

Your email address will not be published. Required fields are marked *