Post your best Lua script examples here

User avatar
By xtal
#32141 I've embedded timer snap shots into the following code...
I expected to see TMR0,1,2,3,4,5 in that sequence .
I'm seeing TMR0,4,5,1,2,3 . my dofile is loading too early
How can I fix it? Code and results listed below..
Code: Select allprint("TMR0 "..tmr.now())
if "a" == "a" then
   local ip, nm, gw
   local tmx
   tmr.alarm (1, 1000, 1, function ( )
print("TMR1 "..tmr.now())
      ip, nm, gw = wifi.sta.getip()
      if ip == nil then
         print ("Wait Connection")
      else
         tmr.stop (1)         
         print ("Mode= "..wifi.getmode(),tmr.now())
         print ("MAC " .. wifi.ap.getmac ( ))
         print (" IP: "..ip.."\n NM: "..nm.."\n GW: "..gw)
         tmx =tmr.now()+10000000   -- 10 sec
print("TMR2 "..tmr.now())
         while (tmx > tmr.now()) do  -- loop for 10 seconds
           tmr.wdclr()
         end
print("TMR3 "..tmr.now())     
      end
   end)
end   
print("TMR4 "..tmr.now())
collectgarbage()
print('dofile',tmr.now())
print("TMR5 "..tmr.now())

if (not not wifi.sta.getip()) or (not not wifi.ap.getip()) then
    dofile("httpserver.lc")(80)   
end


RESULTS---------------------------------------------------------------------------------
Code: Select all dofile('oinit.lua')
set (mode=3)
AP MAC:    5e:cf:7f:01:21:90
Client MAC:    5c:cf:7f:01:21:90
chip:    74128
heap:    18904
TMR0 1629091445
TMR4 1629102700
dofile   1629109011
TMR5 1629113074
cannot open httpserver.lc
> TMR1 1630102848
Wait Connection
TMR1 1631103061
Wait Connection
TMR1 1632102885
Wait Connection
TMR1 1633102840
Mode= 3   1633113765
MAC 5e:cf:7f:01:21:90
 IP: 192.168.1.35
 NM: 255.255.255.0
 GW: 192.168.1.1
TMR2 1633127319
TMR3 1643127464
User avatar
By xtal
#32150 I think I understand what's happening, so far I haven't figured a way around the issue.

Going thru the code I print Trm0 then execute tmr.alarm [function starts and waits call back] so the code immediately continues after the function, which makes things happen before you want.
I been trying to figure a way to stay in 1 place without reset . but so far not successful...
User avatar
By TerryE
#33295 Please read my FAQ which explains all this. Lua is layered over the SDK. The SDK has a simple rule: your tasks shouldn't last more than 10mSec. You've got one which lasts over 10,000 mSec and you wonder why its not working. You have to build your app like a muilti-stranded necklace where each pearl is a callback function and you thread them together by using the API callback mechanisms.

If you think its difficult to read then try just working all this out by going through the code, the sparse SDK documentation, and lots of simple test cases.

To me what you are saying is "I can't be bothered to do reading that I need to do. My code doesn't work. Can someone please spoon-feed me?"