multi files with esp8266

690 Views Asked by At

I am new to the ESP8266 and lua, is it possible to work with multiple files on the ESP8266 ? I have 2 files the first one called foo.lua and it contains this code :

function double(n)
  return n * 2
end

and the other file new.lua just call the first file as following:

require 'foo'
print(foo.double(5))

So can i use this technique with the esp8266 ?

I tried that but when I press save to esp button i get

enter image description here

and

enter image description here

and another popup messages

and these get printed on the console :

> file.remove("foo.lua");
> file.open("foo.lua","w+");
> w = file.writeline
> w([[function double(n)]]);
stdin:1: open a file first
> w([[  return n * 2]]);
stdin:1: open a file firstw([[end]]);
stdin:1: open a file firstw([[]]);
stdin:1: open a file firstw([[print (double(2))]]);
stdin:1: open a file firstfile.close();dofile("foo.lua");
cannot open foo.lua

even when i try to run the file using send to ESP button it works but it will not be saved.

1

There are 1 best solutions below

0
On

There is a way you can achieve that. But you can't just call like foo.double(5). I recommend you to try to put your function inside a class. Then you just have to compile it, with the command:

node.compile("foo.lua")

If you use the explorer, write it in the bottom right of the program, where you have a send button.

To create a class you should use a template, I recommend you to use this one:

function Class(members)
  local mt = {
     __metatable = members;
    __index     = members;
  }
  local function new(_, init)
    return setmetatable(init or {}, mt)
  end
  local function copy(obj, ...)
    local newobj = obj:new(unpack(arg))
    for n,v in pairs(obj) do newobj[n] = v end
    return newobj
  end
  members.new  = members.new  or new
  members.copy = members.copy or copy
  return mt
end

And in your foo.lua just include this:

require'Class'

If you want to use class variables write them here and then

local foo_mt = Class(foo)

After that you can add all the defs you want. Don't forget to finish with return foo;