var.lua save table and function in MUSHclient variables

Posted by Cross.Hate on Tue 01 Aug 2017 11:20 AM — 2 posts, 13,927 views.

#0
-- var.lua
-- ----------------------------------------------------------
-- Accessing MUSHclient variables through the 'var' table.
-- See forum thread:
--  http://www.gammon.com.au/forum/?id=4904

--[[

  * Set a variable by assigning something to it.
  * Delete a variable by assigning nil to it.
  * Get a variable by retrieving its value, will return nil if the variable does not exist.
	add function and table assigning ---- By HaTe@fc2 .
  Examples:
	var.name = "if 1==1 then return 1 else false end" ---  var.name = 1
	var.name = sometable -- tprint(var.name)
    var.target = "kobold"   -- set MUSHclient variable 'target' to kobold
    print (var.target)      -- print contents of MUSHclient variable

--]]

-- ----------------------------------------------------------
transTS=function(v,n,o)
		local n = n
		local o = o or nil
		local tTS = tTs or nil

		if tTs==nil then
			tTs=0
		end
		
		if  o==nil then
			tTs=0
		else
			tTs=tTs+1
		end
		if tTs==0 then
		   o=n..' = {\n'
		end
		for k,v1 in pairs(v) do
			if type(v1)=="table" then
				o=o..k..' = {'
				transTS(v1,n,o)
				o=o..'},\n'
			 else
				if type(v1)~="number" then
				 v1=tostring(v1)
				 o=o..'["'..k..'"] = "'..v1..'",\n'
				else
				o=o..'["'..k..'"] = '..v1..',\n'
				end
			end
		end
		o=o..'\n}'
	return o
end
saved = saved or {}
var = {}
setmetatable (var, 
 { 
 __index = 
 function (t, name)
	if type(loadstring(GetVariable (name)))=="function" then
		loadstring(GetVariable (name))()
		if type(loadstring(saved[name]))=="function" then
			return loadstring(saved[name])()
			else
			return saved[name]
		end
	else
		return GetVariable (name) 
	end
 end,

 __newindex = 
 function (t, name, val) 

 local result
   if val == nil then -- nil deletes it
     result = DeleteVariable (name)
   elseif type(val)=="table" then
		val=transTS(val,'saved.'..name,nil)
		result = SetVariable (name, val) 
	elseif type(loadstring(val)) == "function" and type(val)=="string" then
		result = SetVariable (name, 'saved.'..name..' = '..tostring (val)) 
	else
		result = SetVariable (name, tostring (val)) 
	end 
   -- warn if they are using bad variable names
   if result == error_code.eInvalidObjectLabel then
     error ("Bad variable name '" .. name .. "'", 2)
   end
 end
 })
 
return var
USA Global Moderator #1
Context? (Also, omg the whitespace formatting is bad.) (Also also, MUSHclient is on github at https://github.com/nickgammon/mushclient if you want to make pull requests there directly.)