History variables: Difference between revisions

(Added Wren)
Line 1,208:
Currentvalue is 3
</pre>
 
=={{header|Lua}}==
Lua does not natively support history variables. However, as with other languages here, something roughly equivalent could be implemented with a "stack wrapper". The only complicated issue might be how to treat nil's (null values). The implementation below allows initial nil's, and allows undo()'s back to nil, but does <i>not</i> consider nil as part of the "history".
<lang lua>-- History variables in Lua 6/12/2020 db
local HistoryVariable = {
value = nil, -- nop, for ref only
history = {},
new = function(self)
return setmetatable({},self)
end,
get = function(self)
return self.value
end,
set = function(self, value)
self.history[#self.history+1] = value
self.value = value
end,
undo = function(self)
self.value = self.history[#self.history-1]
self.history[#self.history] = nil
end,
}
HistoryVariable.__index = HistoryVariable
 
local hv = HistoryVariable:new()
print("defined:", hv)
print("value is:", hv:get())
--
hv:set(1); print("set() to:", hv:get())
hv:set(2); print("set() to:", hv:get())
hv:set(3); print("set() to:", hv:get())
--
print("history:", table.concat(hv.history,","))
--
hv:undo(); print("undo() to:", hv:get())
hv:undo(); print("undo() to:", hv:get())
hv:undo(); print("undo() to:", hv:get())</lang>
{{out}}
<pre>defined: table: 0000000000939240
value is: nil
set() to: 1
set() to: 2
set() to: 3
history: 1,2,3
undo() to: 2
undo() to: 1
undo() to: nil</pre>
 
=={{header|M2000 Interpreter}}==
Anonymous user