This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
vvenaya's profile picture

Vv's Programs

Started by vvenaya, 25 February 2012 - 12:03 PM
vvenaya #1
Posted 25 February 2012 - 01:03 PM
I will keep all my code snips in this thread, feel free to use any of it.



PERSISTENT VARIABLES
Allow the player to store and reuse variables over sessions of minecraft, the variables are stored within your /saves/<worldname>/computer/<id>/vvSystem folder

SpoilerUSAGE
to store a variable:
PVar["variableName"]="value"	OR	PVar.variableName="value"

to retrieve a variable:
print (PVar["variableName])   OR   print(PVar.variableName)

CODE


-- ================================================
-- Persistent variables
-- ================================================

PVar={_PVarPath="/vvSystem/"}
setmetatable(PVar,PVar)

PVar._getVariablePath=function(name)
	local filepath = fs.combine(PVar["_PVarPath"],name..".var")
	if not fs.exists(PVar["_PVarPath"]) then
		fs.makeDir(PVar["_PVarPath"])
	end
	return filepath
end

function PVar._assertOnInvalidName(name)  
	if name:sub(1,1)=="_" then
		error("Variable names cannot start with _")
	else
		local invalidCharPos,_ = name:find("[:/*|<>;%s]")
		if invalidCharPos then
			error("Variable names contains invalid character '"..name:sub(invalidCharPos,invalidCharPos).."'")
		end
	end
end

function PVar.__index(tbl,name)
	PVar._assertOnInvalidName(name)
	local f = io.open(PVar._getVariablePath(name), "r")
	if f then
		local content = textutils.unserialize(f:read())
		f:close()
		return content
	else
		return nil
	end
end

function PVar.__newindex(tbl,name,value)
	PVar._assertOnInvalidName(name)
	if value then	  
		local f = io.open(PVar._getVariablePath(name), "w")	
		assert(f,"FAIL: could not open file")
		if f then
			f:write(textutils.serialize(value))
			f:close()
		end
	else
		fs.delete(PVar._getVariablePath(name))
	end
end

-- ================================================
-- Test cases
-- ================================================

_doTestCases=false

if (_doTestCases) then
	local function nz(v) if v then return v else return "nil" end end

	PVar["t"]="test"

	assert(PVar["doesnotexist"]==nil,"FAIL: expected nul for nonexisting variable")
	assert(PVar["t"]=="test","FAIL: Expected 'test' but got:"..nz(PVar["t"]))
	assert(fs.exists(PVar["_PVarPath"].."t.txt"),"FAIL: file expected to exist")
	PVar["t"]=nul
	assert(PVar["t"]==nul,"FAIL: deleted variable should return nul")
	assert(not fs.exists(PVar["_PVarPath"].."t.txt"),"FAIL: file should be deleted")
	PVar["t"]=6
	assert(type(PVar["t"])=="number","FAIL: returned wrong type")
	print("Test case completed OK")
end





ASSERTION CLASS (WIP)
Unit Testing class (this is a work in progress)

SpoilerMETHODS
Assert.hasError - Test if a function encounter an error()
Assert.hasNoError - Test if a function did not encounter an error()

CODE






Assert={}

function Assert.hasError(funcWithParams, arg1, arg2)
	local status,err = pcall(unpack(funcWithParams))
	if status or (arg2 and arg1~=err:sub(err:find("%s")+1)) then
		if arg2  then
			error(arg2)
		elseif arg1 then
			error(arg1)
		else
			error("expected error did not trigger")
		end
	end
end

function Assert.hasNoError(funcWithParams, optionalMessage)
	local status,err = pcall(unpack(funcWithParams))

	if not status then
		if optionalMessage  then
			error(optionalMessage)
		else
			error("expected no error but got: " .. err)
		end
	end
end

-- =================================================

_doTestCases=false

if (_doTestCases) then
	-- =[hasError]=
	Assert.hasError({function() error("test") end},"test", "FAILED: Expected error (1)")
	Assert.hasError({function() error("test") end},"FAILED: Expected error (2)")
	Assert.hasError({function() error("test") end})
	assert(not pcall(Assert.hasError, {function() end}),"FAILED: hasError(4): assert should not trigger when no error has detected")
	-- =[hasNoError]=
	Assert.hasNoError({function() end},"FAILED: HasNoError(1): Expected no errors")
	assert(not pcall(Assert.hasNoError, {function() error("test") end} ,"dummy"),"FAILED: HasNoError(2): hasNoError should have failed, but succeeded")
	assert(not pcall(Assert.hasNoError, {function() error("someError") end}),"FAILED: HasNoError(3): hasNoError should have failed, but succeeded")
	-- = ALL DONE
	print("TestCases OK")
end
</id></worldname>
vvenaya #2
Posted 26 February 2012 - 08:22 AM
small fix to Persistent variables. and added spoiler to OP
Kane Hart #3
Posted 29 February 2012 - 11:00 AM
bump for friend :o/>/>