7241
Mach4 General Discussion / Re: Lua
« on: January 07, 2017, 01:42:24 AM »
Hi dude1,
just having a look at your code. Note that you have numbered the entries in the signal table. Is it necessary?
This is from the default screen load script:
They are not numbered. The SigLib table can be searched by key and the key can be alphanumeric, a handy and powerful property in LUA.
The signal script can therefore be simplified, this is the default signal script:
This means that you don't have to use multiple IF statements, should sig be mentioned in your SigLib, ie a signal of interest, it returns non-nil and therefore
executes the function associated with that key with state as argument.
In fact LUA is a bit more crafty than that; if sig exists as a key in SigLib it returns the function entire, I think that property is called 'functions as first class values'.
Another extremely powerful and flexible property of LUA. In this instance of course we don't require the function but just that it exists, ie non-nil.
If you could be sure that EVERY possible sig is in the table then the script could be simplified even further:
This idea of bandying about a function, with all its statements, as simply as a single number is a real eye opener to me.
Craig
just having a look at your code. Note that you have numbered the entries in the signal table. Is it necessary?
This is from the default screen load script:
Code: [Select]
SigLib = {
[mc.OSIG_MACHINE_ENABLED] = function (state)
machEnabled = state;
ButtonEnable()
end,
[mc.ISIG_INPUT0] = function (state)
end,
[mc.ISIG_INPUT1] = function (state)
-- if (state == 1) then
-- CycleStart()
-- --else
-- --mc.mcCntlFeedHold (0)
-- end
end,
They are not numbered. The SigLib table can be searched by key and the key can be alphanumeric, a handy and powerful property in LUA.
The signal script can therefore be simplified, this is the default signal script:
Code: [Select]
if SigLib[sig] ~= nil then
SigLib[sig](state);
end
This means that you don't have to use multiple IF statements, should sig be mentioned in your SigLib, ie a signal of interest, it returns non-nil and therefore
executes the function associated with that key with state as argument.
In fact LUA is a bit more crafty than that; if sig exists as a key in SigLib it returns the function entire, I think that property is called 'functions as first class values'.
Another extremely powerful and flexible property of LUA. In this instance of course we don't require the function but just that it exists, ie non-nil.
If you could be sure that EVERY possible sig is in the table then the script could be simplified even further:
Code: [Select]
SigLib(sig)(state);
This idea of bandying about a function, with all its statements, as simply as a single number is a real eye opener to me.
Craig