Need Help on my Lua Script to force a certain Value permanently constantly

Want Cheat Engine to do something specific and no idea how to do that, ask here. (From simple scripts to full trainers and extensions)
User avatar
dreamcactus
Expert Cheater
Expert Cheater
Posts: 108
Joined: Sat Jul 06, 2019 12:21 pm
Reputation: 0

Need Help on my Lua Script to force a certain Value permanently constantly

Post by dreamcactus »

so in this Lua Script i got , well it dont force a certain Value and make sure its constantly forced for listed Cheat thats set to autoenable on start, named>

"max jump everywhere - change value to 60",

Code: Select all

controlMainForm = getMainForm()
AddressList = getAddressList()

if getCEVersion == nil or getCEVersion() < 6.5 then
	messageDialog('It is recommended to use at least Cheat Engine 6.7! (Your Version: '..getCEVersion()..')', mtError, mbOK)
end

errorOnLookupFailure(false)
setGlobalDelayBetweenHotkeyActivation(200)
DefaultProccessName = "pcsx2.exe"
strings_add(getAutoAttachList(), DefaultProccessName)

PRIVATETABLE, SWITCHSUPPORT = true, false

function cycleFullCompact(sender,force)
	local state = not(compactmenuitem.Caption == 'Compact View Mode')
	if force~=nil then state = not force end
	compactmenuitem.Caption = state and 'Compact View Mode' or 'Full View Mode'
	getMainForm().Splitter1.Visible = state
	getMainForm().Panel4.Visible = state
	getMainForm().Panel5.Visible = state
end

function addCompactMenu()
	if compactmenualreadyexists then return end
	local parent = getMainForm().Menu.Items
	compactmenuitem = createMenuItem(parent); parent.add(compactmenuitem)
	compactmenuitem.Caption = 'Compact View Mode'
	compactmenuitem.OnClick = cycleFullCompact
	compactmenualreadyexists = 'yes'
end
addCompactMenu()
cycleFullCompact(nil, true)


----
local format = string.format
local strE = ''

function split(s, delimiter)
	result = {}
	for match in (s .. delimiter):gmatch('(.-)' .. delimiter) do
		table.insert(result, match)
	end
	return result
end

local le = '\r\n'
FileName = "MemoryRecordValues.txt"
NameList = {
	"max jump everywhere - change value to 60",
}

function saveValues()

	local fileStr = strE
	if stateName == nil then
		stateName = I2CETState.DefaultState
	end
	for i = 1, #NameList do
		local mr = AddressList.getMemoryRecordByDescription(NameList[i])
		if mr ~= nil then
			local value = mr.Value
			fileStr = fileStr .. value .. le
		else
			error(format('The memory record was not found, "%s"', NameList[i]))
		end
	end
	local f, err = io.open(FileName, 'w')
	if err then
		error(format('The file could not be opened, "%s", %s', FileName, err))
	elseif f and not err then
		f:write(fileStr)
		f:close()
	end
end

function loadValues()
	Logger.debugf('Using state file name: "%s"', FileName)
	local fileStr = nil
	local f, err = io.open(FileName, 'r')
	if err then
		error(format('The file could not be opened, "%s", %s', FileName, err))
	elseif f and not err then
		fileStr = f:read('*all')
		f:close()
	else
		error(format('The file could not be opened, "%s"', FileName))
	end
	if fileStr == nil then
		error(format('File string was nil'))
		return
	end
	local lines = split(fileStr, le)
	for i, v in ipairs(lines) do
		if v ~= nil and v ~= strE then
			local mr = AddressList.getMemoryRecordByDescription(NameList[i])
			if mr ~= nil then
				mr.Value = v
			else
				error(format('The memory record was not found, "%s"', NameList[i]))
			end
		end
	end
end
----


PROCESS_NAME = 'pcsx2.exe'
--------
-------- Auto Attach
--------
local autoAttachTimer = nil ---- variable to hold timer object
local autoAttachTimerInterval = 100 ---- Timer intervals are in milliseconds
local autoAttachTimerTicks = 0 ---- variable to count number of times the timer has run
local autoAttachTimerTickMax = 5000 ---- Set to zero to disable ticks max
local function autoAttachTimer_tick(timer) ---- Timer tick call back
	---- Destroy timer if max ticks is reached
	if autoAttachTimerTickMax > 0 and autoAttachTimerTicks >= autoAttachTimerTickMax then
		timer.destroy()
	end
	---- Check if process is running
	if getProcessIDFromProcessName(PROCESS_NAME) ~= nil then
		timer.destroy() ---- Destroy timer
		openProcess(PROCESS_NAME) ---- Open the process
		-- getAddressList().getMemoryRecordByDescription("max jump everywhere - change value to 60)").active=true
		--
		---- Just a way to do this with the NameList,
		----     thus you can just add to the list to make it work with other memory records.
		for i = 1, #NameList do
			local mr = AddressList.getMemoryRecordByDescription(NameList[i])
			if mr ~= nil then
				mr.Active = true
			else
				error(format('The memory record was not found, "%s"', NameList[i]))
			end
		end
	end
	autoAttachTimerTicks = autoAttachTimerTicks + 1 ---- Increase ticks
end
autoAttachTimer = createTimer(getMainForm()) ---- Create timer with the main form as it's parent
autoAttachTimer.Interval = autoAttachTimerInterval ---- Set timer interval
autoAttachTimer.OnTimer = autoAttachTimer_tick ---- Set timer tick call back

User avatar
TheyCallMeTim13
Administration
Administration
Posts: 1660
Joined: Fri Mar 03, 2017 12:31 am
Reputation: 876

Re: Need Help on my Lua Script to force a certain Value permanently constantly

Post by TheyCallMeTim13 »

Hay, I recognize some of this code; had to grin when I saw the logger call.


So if you run this script, then try and run saveValues, you get and error on line 58 "Attempt to index a nil value (global 'I2CETState')". So looking at the code around line 58, you'll find this:

Code: Select all

	if stateName == nil then
		stateName = I2CETState.DefaultState
	end
So it's still looking for a state name, but it's not actually using it so that can just be removed. Then it will run and create the file, so long as the NameList has corresponding memory records with descriptions that are an exact match to the list.

Then if you run loadValues you get an error on line 76 "Attempt to index a nil value (global 'Logger')". So you need to add a logger or remove that stuff, but it's only on the first line for the loadValues function. So let's just go with removing it. At that point it will both save and load.

Code: Select all

controlMainForm = getMainForm()
AddressList = getAddressList()

if getCEVersion == nil or getCEVersion() < 6.5 then
	messageDialog('It is recommended to use at least Cheat Engine 6.7! (Your Version: '..getCEVersion()..')', mtError, mbOK)
end

errorOnLookupFailure(false)
setGlobalDelayBetweenHotkeyActivation(200)
DefaultProccessName = "pcsx2.exe"
strings_add(getAutoAttachList(), DefaultProccessName)

PRIVATETABLE, SWITCHSUPPORT = true, false

function cycleFullCompact(sender,force)
	local state = not(compactmenuitem.Caption == 'Compact View Mode')
	if force~=nil then state = not force end
	compactmenuitem.Caption = state and 'Compact View Mode' or 'Full View Mode'
	getMainForm().Splitter1.Visible = state
	getMainForm().Panel4.Visible = state
	getMainForm().Panel5.Visible = state
end

function addCompactMenu()
	if compactmenualreadyexists then return end
	local parent = getMainForm().Menu.Items
	compactmenuitem = createMenuItem(parent); parent.add(compactmenuitem)
	compactmenuitem.Caption = 'Compact View Mode'
	compactmenuitem.OnClick = cycleFullCompact
	compactmenualreadyexists = 'yes'
end
addCompactMenu()
cycleFullCompact(nil, true)


----
local format = string.format
local strE = ''

function split(s, delimiter)
	result = {}
	for match in (s .. delimiter):gmatch('(.-)' .. delimiter) do
		table.insert(result, match)
	end
	return result
end

local le = '\r\n'
FileName = "MemoryRecordValues.txt"
NameList = {
	'memTestValues+0',
	'memTestValues+4',
}

function saveValues()
	local fileStr = strE
	for i = 1, #NameList do
		local mr = AddressList.getMemoryRecordByDescription(NameList[i])
		if mr ~= nil then
			local value = mr.Value
			fileStr = fileStr .. value .. le
		else
			error(format('The memory record was not found, "%s"', NameList[i]))
		end
	end
	local f, err = io.open(FileName, 'w')
	if err then
		error(format('The file could not be opened, "%s", %s', FileName, err))
	elseif f and not err then
		f:write(fileStr)
		f:close()
	end
end

function loadValues()
	local fileStr = nil
	local f, err = io.open(FileName, 'r')
	if err then
		error(format('The file could not be opened, "%s", %s', FileName, err))
	elseif f and not err then
		fileStr = f:read('*all')
		f:close()
	else
		error(format('The file could not be opened, "%s"', FileName))
	end
	if fileStr == nil then
		error(format('File string was nil'))
		return
	end
	local lines = split(fileStr, le)
	for i, v in ipairs(lines) do
		if v ~= nil and v ~= strE then
			local mr = AddressList.getMemoryRecordByDescription(NameList[i])
			if mr ~= nil then
				mr.Value = v
			else
				error(format('The memory record was not found, "%s"', NameList[i]))
			end
		end
	end
end
----


PROCESS_NAME = 'pcsx2.exe'
--------
-------- Auto Attach
--------
local autoAttachTimer = nil ---- variable to hold timer object
local autoAttachTimerInterval = 100 ---- Timer intervals are in milliseconds
local autoAttachTimerTicks = 0 ---- variable to count number of times the timer has run
local autoAttachTimerTickMax = 5000 ---- Set to zero to disable ticks max
local function autoAttachTimer_tick(timer) ---- Timer tick call back
	---- Destroy timer if max ticks is reached
	if autoAttachTimerTickMax > 0 and autoAttachTimerTicks >= autoAttachTimerTickMax then
		timer.destroy()
	end
	---- Check if process is running
	if getProcessIDFromProcessName(PROCESS_NAME) ~= nil then
		timer.destroy() ---- Destroy timer
		openProcess(PROCESS_NAME) ---- Open the process
		-- getAddressList().getMemoryRecordByDescription("max jump everywhere - change value to 60)").active=true
		--
		---- Just a way to do this with the NameList,
		----     thus you can just add to the list to make it work with other memory records.
		for i = 1, #NameList do
			local mr = AddressList.getMemoryRecordByDescription(NameList[i])
			if mr ~= nil then
				mr.Active = true
			else
				error(format('The memory record was not found, "%s"', NameList[i]))
			end
		end
	end
	autoAttachTimerTicks = autoAttachTimerTicks + 1 ---- Increase ticks
end
autoAttachTimer = createTimer(getMainForm()) ---- Create timer with the main form as it's parent
autoAttachTimer.Interval = autoAttachTimerInterval ---- Set timer interval
autoAttachTimer.OnTimer = autoAttachTimer_tick ---- Set timer tick call back

But I'm thinking you'd want to set it up to look for a special start to the memory records description, say "AUTO SET:" or some thing. Then store the memory record's id and the value on each line of the save file, just make it use a special delimiter between the id and value; so commas and what not can still be used in descriptions. So you'd also need to split each line after splitting the save file lines when loading the values. This way you don't need to add the descriptions to the name list, and memory records can be moved without needing to update the name list.

EDIT: I might do some messing with my table state module. I'll post it here if I do.

User avatar
TheyCallMeTim13
Administration
Administration
Posts: 1660
Joined: Fri Mar 03, 2017 12:31 am
Reputation: 876

Re: Need Help on my Lua Script to force a certain Value permanently constantly

Post by TheyCallMeTim13 »

So I set it up to look for "AUTO SET:" at the start of the memory record's description for saving and loading values. It still enables scripts and since it waits for the script to be enabled it can now set script values too, so long as they are nested under the script.

Here's a stripped down version of the module, to make things simpler it has a dummy logger and just sets global functions from the module functions. But to set any settings you'll have to change the script defaults or index the module.

EDIT: I remembered you said something about "constantly forced" so I set it up to also check if saved values are activated (freezen) and activate set values when loading a state.

Code: Select all

local format = string.format
local strE = string.empty or STRING_EMPTY or ''
local t = translate

if MainForm == nil then
	MainForm = getMainForm()
end
if AddressList == nil then
	AddressList = getAddressList()
end



I2CETState = {
	DefaultState = 'default', 
	SaveFileName = 'I2CETState.${StateName}.txt', 
	UseMemoryRecordDescriptions = false, 
	LineEnd = '\n', 
	DisableBeforeLoad = true, 
	PrintStatus = false, --true, 
	SaveValueMatch = 'AUTO SET:',
	LineDelimiter = '<SEP>',
	ScriptID = 'I2CETStateSCRIPTID',
}

local Logger = {
	LEVELS = {
		OFF = 0, 
		FATAL = 1, 
		ERROR = 2, 
		WARN = 3, 
		INFO = 4, 
		DEBUG = 5, 
		TRACE = 6
	}, 
	Level = 0,
}
for k, v in pairs(Logger.LEVELS) do
	Logger[k:lower()] = function( ... ) return end
	Logger[k:lower() .. 'f'] = function( ... ) return end
	-- Logger[k:lower()] = function(msg, ex) return print(msg, ex) end
	-- Logger[k:lower() .. 'f'] = function(msg, ... ) return print(string.format(msg, ... )) end
end

local function split(s, delimiter)
	result = {}
	for match in (s .. delimiter):gmatch('(.-)' .. delimiter) do
		table.insert(result, match)
	end
	return result
end

local function interp(s, tbl)
	if s == nil then return end
	return (s:gsub('($%b{})', function(w) return tbl[w:sub(3, -2)] or w end))
end


function I2CETState.saveTableState(stateName)
	if not inMainThread() then
		synchronize(function(thread)
			I2CETState.saveTableState(stateName)
		end)
		return
	end
	Logger.trace()
	if I2CETState.PrintStatus and Logger.Level <= Logger.LEVELS.WARN then
		getLuaEngine().show()
	end
	if I2CETState.PrintStatus and Logger.Level <= Logger.LEVELS.WARN then
		print(format('Saving Table State:  %s', stateName))
	end
	local le = I2CETState.LineEnd
	local ld = I2CETState.LineDelimiter
	local sid = I2CETState.ScriptID
	local svm = I2CETState.SaveValueMatch
	if stateName == nil then
		stateName = I2CETState.DefaultState
	end
	local fileName = interp(I2CETState.SaveFileName, { StateName = stateName } )
	Logger.debugf('Using state file name: "%s"', fileName)
	local fileStr = strE
	for i = 0, AddressList.Count - 1 do
		local mr = AddressList.getMemoryRecord(i)
		if mr.Description ~= '_[  I2CETState  ]_' 
		and mr.Description ~= '_[  Save Table State  ]_' 
		and mr.Description ~= '_[  Load Table State  ]_' 
		and mr.Description:sub(0, 16) ~= 'Load Table State'
		and mr.Description:sub(0, 16) ~= 'Save Table State' then
			local id = tostring(mr.ID)
			if I2CETState.UseMemoryRecordDescriptions then
				id = mr.Description
			end
			if mr.Type == vtAutoAssembler and mr.Active then
				Logger.debugf('Saving script state: %d, %d, "%s"', mr.Index, mr.ID, mr.Description)
				fileStr = fileStr..id..ld..sid..ld..tostring(mr.Active)..le
			elseif mr.Description:sub(0, #svm) == svm and mr.Value ~= '??' then
				Logger.debugf('Saving value: %d, %d, "%s", %s', mr.Index, mr.ID, mr.Description, mr.Value)
				fileStr = fileStr..id..ld..mr.Value..ld..tostring(mr.Active)..le
			end
		end
	end
	local f, err = io.open(fileName, 'w')
	if err then
		Logger.errorf('The file could not be opened, "%s", %s', fileName, err)
	elseif f and not err then
		f:write(fileStr)
		f:close()
	end
end
saveTableState = I2CETState.saveTableState


function I2CETState.loadTableState(stateName)
	if not inMainThread() then
		synchronize(function(thread)
			I2CETState.loadTableState(stateName)
		end)
		return
	end
	Logger.trace()
	if I2CETState.PrintStatus and Logger.Level <= Logger.LEVELS.WARN then
		getLuaEngine().show()
	end
	if I2CETState.PrintStatus and Logger.Level <= Logger.LEVELS.WARN then
		print(format('Setting Table State:  %s', stateName))
	end
	local le = I2CETState.LineEnd
	local ld = I2CETState.LineDelimiter
	local sid = I2CETState.ScriptID
	local svm = I2CETState.SaveValueMatch
	if stateName == nil then
		stateName = I2CETState.DefaultState
	end
	local fileName = interp(I2CETState.SaveFileName, { StateName = stateName } )
	Logger.debugf('Using state file name: "%s"', fileName)
	local fileStr = nil
	local f, err = io.open(fileName, 'r')
	if err then
		Logger.infof('The local file could not be opened, "%s", %s', fileName, err)
		local tableFile = findTableFile(fileName)
		if tableFile == nil then
			Logger.warnf('file not found, "%s"', fileName)
			return
		end
		local stream = tableFile.getData()
		local bytes = stream.read(stream.Size)
		for i = 1, #bytes do
			if fileStr == nil then
				fileStr = strE
			end
			fileStr = fileStr .. string.char(bytes[i])
		end
	elseif f and not err then
		fileStr = f:read('*all')
		f:close()
	else
		Logger.errorf('The file could not be opened, "%s"', fileName)
	end
	if I2CETState.DisableBeforeLoad then
		for i = AddressList.Count - 1, 0, -1 do
			local mr = AddressList.getMemoryRecord(i)
			if mr.Description ~= '_[  I2CETState  ]_' 
		and mr.Description ~= '_[  Save Table State  ]_' 
		and mr.Description ~= '_[  Load Table State  ]_' 
			and mr.Description:sub(0, 16) ~= 'Load Table State'
			and mr.Description:sub(0, 16) ~= 'Save Table State' then
				if mr.Active then
					Logger.infof('Disabling memory record: %d, %d, "%s"', mr.Index, mr.ID, mr.Description)
					if I2CETState.PrintStatus and Logger.Level <= Logger.LEVELS.WARN then
						print(format('Disabling:  %s', mr.Description))
					end
					mr.Active = false
					while mr.Async and mr.AsyncProcessing do
						checkSynchronize()
					end
					sleep(0)
				end
			end
		end
		sleep(0)
	end
	if fileStr == nil then
		Logger.info('File string was nil')
		return
	end
	local lines = split(fileStr, I2CETState.LineEnd)
	for i, v in ipairs(lines) do
		if v ~= nil and v ~= strE then
			local data = split(v, I2CETState.LineDelimiter)
			local mr = nil
			if I2CETState.UseMemoryRecordDescriptions then
				mr = AddressList.getMemoryRecordByDescription(data[1])
			else
				mr = AddressList.getMemoryRecordByID(tonumber(data[1]))
			end
			if mr ~= nil then
				if mr.Type == vtAutoAssembler and mr.Active == false
				and data[2] == sid and data[3] == tostring(true) then
					Logger.infof('Enabling memory record: %d, %d, "%s"', mr.Index, mr.ID, mr.Description)
					if I2CETState.PrintStatus and Logger.Level <= Logger.LEVELS.WARN then
						print(format('Enabling:  "%s"', mr.Description))
					end
					mr.Active = true
					while mr.Async and mr.AsyncProcessing do
						checkSynchronize()
					end
					sleep(0)
				elseif mr.Type ~= vtAutoAssembler and mr.Description:sub(0, #svm) == svm then
					if mr.Value == '??' then
						Logger.warnf('Memory record value not set: %d, %d, "%s", "%s"', mr.Index, mr.ID, mr.Description, mr.Value)
						if I2CETState.PrintStatus and Logger.Level <= Logger.LEVELS.WARN then
							print(format('Memory record value not set:  "%s", "%s"', mr.Description, mr.Value))
						end
					else
						Logger.infof('Setting memory record: %d, %d, "%s", %s, %s', mr.Index, mr.ID, mr.Description, data[1], data[2])
						if I2CETState.PrintStatus and Logger.Level <= Logger.LEVELS.WARN then
							print(format('Setting:  "%s", %s', mr.Description, data[2]))
						end
						mr.Value = data[2]
						if data[3] == tostring(true) then
							mr.Active = true
						end
					end
				end
			else
				Logger.errorf('Memory record not found: "%s", "%s", "%s"', data[1], data[2], v)
			end
		end
	end
	if I2CETState.PrintStatus and Logger.Level <= Logger.LEVELS.WARN then
		print(format('Table State Set:  %s', stateName))
		getLuaEngine().hide()
	end
end
loadTableState = I2CETState.loadTableState


return I2CETState

User avatar
dreamcactus
Expert Cheater
Expert Cheater
Posts: 108
Joined: Sat Jul 06, 2019 12:21 pm
Reputation: 0

Re: Need Help on my Lua Script to force a certain Value permanently constantly

Post by dreamcactus »

yeah , your the code master here my dude, of course i used parts of yours lols, anyhow so is this correct then now? this code will autosave enabled cheats and autosave values i enter no matter how many subfolders a cheat has aka levels , then make sure to force said values aka freeze so they dont get changed and when i exit CT and restart it , i wont have to do the same process over again right? also have i understood this properly ...i dont have to manual enter one cheat after another in the list? that would be freakin killer, also said function im wanting is essentially what pretty much most CTs should have built in by default aka streamlined user experience imo, anyhow this is the said code , hope i did it right>

Code: Select all

controlMainForm = getMainForm()
AddressList = getAddressList()

if getCEVersion == nil or getCEVersion() < 6.5 then
	messageDialog('It is recommended to use at least Cheat Engine 6.7! (Your Version: '..getCEVersion()..')', mtError, mbOK)
end

errorOnLookupFailure(false)
setGlobalDelayBetweenHotkeyActivation(200)
DefaultProccessName = "pcsx2.exe"
strings_add(getAutoAttachList(), DefaultProccessName)

PRIVATETABLE, SWITCHSUPPORT = true, false

function cycleFullCompact(sender,force)
	local state = not(compactmenuitem.Caption == 'Compact View Mode')
	if force~=nil then state = not force end
	compactmenuitem.Caption = state and 'Compact View Mode' or 'Full View Mode'
	getMainForm().Splitter1.Visible = state
	getMainForm().Panel4.Visible = state
	getMainForm().Panel5.Visible = state
end

function addCompactMenu()
	if compactmenualreadyexists then return end
	local parent = getMainForm().Menu.Items
	compactmenuitem = createMenuItem(parent); parent.add(compactmenuitem)
	compactmenuitem.Caption = 'Compact View Mode'
	compactmenuitem.OnClick = cycleFullCompact
	compactmenualreadyexists = 'yes'
end
addCompactMenu()
cycleFullCompact(nil, true)


----
local format = string.format
local strE = string.empty or STRING_EMPTY or ''
local t = translate

if MainForm == nil then
	MainForm = getMainForm()
end
if AddressList == nil then
	AddressList = getAddressList()
end



I2CETState = {
	DefaultState = 'default',
	SaveFileName = 'I2CETState.${StateName}.txt',
	UseMemoryRecordDescriptions = false,
	LineEnd = '\n',
	DisableBeforeLoad = true,
	PrintStatus = false, --true,
	SaveValueMatch = 'AUTO SET:',
	LineDelimiter = '',
	ScriptID = 'I2CETStateSCRIPTID',
}

local Logger = {
	LEVELS = {
		OFF = 0,
		FATAL = 1,
		ERROR = 2,
		WARN = 3,
		INFO = 4,
		DEBUG = 5,
		TRACE = 6
	},
	Level = 0,
}
for k, v in pairs(Logger.LEVELS) do
	Logger[k:lower()] = function( ... ) return end
	Logger[k:lower() .. 'f'] = function( ... ) return end
	-- Logger[k:lower()] = function(msg, ex) return print(msg, ex) end
	-- Logger[k:lower() .. 'f'] = function(msg, ... ) return print(string.format(msg, ... )) end
end

local function split(s, delimiter)
	result = {}
	for match in (s .. delimiter):gmatch('(.-)' .. delimiter) do
		table.insert(result, match)
	end
	return result
end

local function interp(s, tbl)
	if s == nil then return end
	return (s:gsub('($%b{})', function(w) return tbl[w:sub(3, -2)] or w end))
end


function I2CETState.saveTableState(stateName)
	if not inMainThread() then
		synchronize(function(thread)
			I2CETState.saveTableState(stateName)
		end)
		return
	end
	Logger.trace()
	if I2CETState.PrintStatus and Logger.Level <= Logger.LEVELS.WARN then
		getLuaEngine().show()
	end
	if I2CETState.PrintStatus and Logger.Level <= Logger.LEVELS.WARN then
		print(format('Saving Table State:  %s', stateName))
	end
	local le = I2CETState.LineEnd
	local ld = I2CETState.LineDelimiter
	local sid = I2CETState.ScriptID
	local svm = I2CETState.SaveValueMatch
	if stateName == nil then
		stateName = I2CETState.DefaultState
	end
	local fileName = interp(I2CETState.SaveFileName, { StateName = stateName } )
	Logger.debugf('Using state file name: "%s"', fileName)
	local fileStr = strE
	for i = 0, AddressList.Count - 1 do
		local mr = AddressList.getMemoryRecord(i)
		if mr.Description ~= '_[  I2CETState  ]_'
		and mr.Description ~= '_[  Save Table State  ]_'
		and mr.Description ~= '_[  Load Table State  ]_'
		and mr.Description:sub(0, 16) ~= 'Load Table State'
		and mr.Description:sub(0, 16) ~= 'Save Table State' then
			local id = tostring(mr.ID)
			if I2CETState.UseMemoryRecordDescriptions then
				id = mr.Description
			end
			if mr.Type == vtAutoAssembler and mr.Active then
				Logger.debugf('Saving script state: %d, %d, "%s"', mr.Index, mr.ID, mr.Description)
				fileStr = fileStr..id..ld..sid..ld..tostring(mr.Active)..le
			elseif mr.Description:sub(0, #svm) == svm and mr.Value ~= '??' then
				Logger.debugf('Saving value: %d, %d, "%s", %s', mr.Index, mr.ID, mr.Description, mr.Value)
				fileStr = fileStr..id..ld..mr.Value..ld..tostring(mr.Active)..le
			end
		end
	end
	local f, err = io.open(fileName, 'w')
	if err then
		Logger.errorf('The file could not be opened, "%s", %s', fileName, err)
	elseif f and not err then
		f:write(fileStr)
		f:close()
	end
end
saveTableState = I2CETState.saveTableState


function I2CETState.loadTableState(stateName)
	if not inMainThread() then
		synchronize(function(thread)
			I2CETState.loadTableState(stateName)
		end)
		return
	end
	Logger.trace()
	if I2CETState.PrintStatus and Logger.Level <= Logger.LEVELS.WARN then
		getLuaEngine().show()
	end
	if I2CETState.PrintStatus and Logger.Level <= Logger.LEVELS.WARN then
		print(format('Setting Table State:  %s', stateName))
	end
	local le = I2CETState.LineEnd
	local ld = I2CETState.LineDelimiter
	local sid = I2CETState.ScriptID
	local svm = I2CETState.SaveValueMatch
	if stateName == nil then
		stateName = I2CETState.DefaultState
	end
	local fileName = interp(I2CETState.SaveFileName, { StateName = stateName } )
	Logger.debugf('Using state file name: "%s"', fileName)
	local fileStr = nil
	local f, err = io.open(fileName, 'r')
	if err then
		Logger.infof('The local file could not be opened, "%s", %s', fileName, err)
		local tableFile = findTableFile(fileName)
		if tableFile == nil then
			Logger.warnf('file not found, "%s"', fileName)
			return
		end
		local stream = tableFile.getData()
		local bytes = stream.read(stream.Size)
		for i = 1, #bytes do
			if fileStr == nil then
				fileStr = strE
			end
			fileStr = fileStr .. string.char(bytes[i])
		end
	elseif f and not err then
		fileStr = f:read('*all')
		f:close()
	else
		Logger.errorf('The file could not be opened, "%s"', fileName)
	end
	if I2CETState.DisableBeforeLoad then
		for i = AddressList.Count - 1, 0, -1 do
			local mr = AddressList.getMemoryRecord(i)
			if mr.Description ~= '_[  I2CETState  ]_'
		and mr.Description ~= '_[  Save Table State  ]_'
		and mr.Description ~= '_[  Load Table State  ]_'
			and mr.Description:sub(0, 16) ~= 'Load Table State'
			and mr.Description:sub(0, 16) ~= 'Save Table State' then
				if mr.Active then
					Logger.infof('Disabling memory record: %d, %d, "%s"', mr.Index, mr.ID, mr.Description)
					if I2CETState.PrintStatus and Logger.Level <= Logger.LEVELS.WARN then
						print(format('Disabling:  %s', mr.Description))
					end
					mr.Active = false
					while mr.Async and mr.AsyncProcessing do
						checkSynchronize()
					end
					sleep(0)
				end
			end
		end
		sleep(0)
	end
	if fileStr == nil then
		Logger.info('File string was nil')
		return
	end
	local lines = split(fileStr, I2CETState.LineEnd)
	for i, v in ipairs(lines) do
		if v ~= nil and v ~= strE then
			local data = split(v, I2CETState.LineDelimiter)
			local mr = nil
			if I2CETState.UseMemoryRecordDescriptions then
				mr = AddressList.getMemoryRecordByDescription(data[1])
			else
				mr = AddressList.getMemoryRecordByID(tonumber(data[1]))
			end
			if mr ~= nil then
				if mr.Type == vtAutoAssembler and mr.Active == false
				and data[2] == sid and data[3] == tostring(true) then
					Logger.infof('Enabling memory record: %d, %d, "%s"', mr.Index, mr.ID, mr.Description)
					if I2CETState.PrintStatus and Logger.Level <= Logger.LEVELS.WARN then
						print(format('Enabling:  "%s"', mr.Description))
					end
					mr.Active = true
					while mr.Async and mr.AsyncProcessing do
						checkSynchronize()
					end
					sleep(0)
				elseif mr.Type ~= vtAutoAssembler and mr.Description:sub(0, #svm) == svm then
					if mr.Value == '??' then
						Logger.warnf('Memory record value not set: %d, %d, "%s", "%s"', mr.Index, mr.ID, mr.Description, mr.Value)
						if I2CETState.PrintStatus and Logger.Level <= Logger.LEVELS.WARN then
							print(format('Memory record value not set:  "%s", "%s"', mr.Description, mr.Value))
						end
					else
						Logger.infof('Setting memory record: %d, %d, "%s", %s, %s', mr.Index, mr.ID, mr.Description, data[1], data[2])
						if I2CETState.PrintStatus and Logger.Level <= Logger.LEVELS.WARN then
							print(format('Setting:  "%s", %s', mr.Description, data[2]))
						end
						mr.Value = data[2]
						if data[3] == tostring(true) then
							mr.Active = true
						end
					end
				end
			else
				Logger.errorf('Memory record not found: "%s", "%s", "%s"', data[1], data[2], v)
			end
		end
	end
	if I2CETState.PrintStatus and Logger.Level <= Logger.LEVELS.WARN then
		print(format('Table State Set:  %s', stateName))
		getLuaEngine().hide()
	end
end
loadTableState = I2CETState.loadTableState


return I2CETState
----


PROCESS_NAME = 'pcsx2.exe'
--------
-------- Auto Attach
--------
local autoAttachTimer = nil ---- variable to hold timer object
local autoAttachTimerInterval = 100 ---- Timer intervals are in milliseconds
local autoAttachTimerTicks = 0 ---- variable to count number of times the timer has run
local autoAttachTimerTickMax = 5000 ---- Set to zero to disable ticks max
local function autoAttachTimer_tick(timer) ---- Timer tick call back
	---- Destroy timer if max ticks is reached
	if autoAttachTimerTickMax > 0 and autoAttachTimerTicks >= autoAttachTimerTickMax then
		timer.destroy()
	end
	---- Check if process is running
	if getProcessIDFromProcessName(PROCESS_NAME) ~= nil then
		timer.destroy() ---- Destroy timer
		openProcess(PROCESS_NAME) ---- Open the process
		-- getAddressList().getMemoryRecordByDescription("max jump everywhere - change value to 60)").active=true
		--
		---- Just a way to do this with the NameList,
		----     thus you can just add to the list to make it work with other memory records.
		for i = 1, #NameList do
			local mr = AddressList.getMemoryRecordByDescription(NameList[i])
			if mr ~= nil then
				mr.Active = true
			else
				error(format('The memory record was not found, "%s"', NameList[i]))
			end
		end
	end
	autoAttachTimerTicks = autoAttachTimerTicks + 1 ---- Increase ticks
end
autoAttachTimer = createTimer(getMainForm()) ---- Create timer with the main form as it's parent
autoAttachTimer.Interval = autoAttachTimerInterval ---- Set timer interval
autoAttachTimer.OnTimer = autoAttachTimer_tick ---- Set timer tick call back

User avatar
TheyCallMeTim13
Administration
Administration
Posts: 1660
Joined: Fri Mar 03, 2017 12:31 am
Reputation: 876

Re: Need Help on my Lua Script to force a certain Value permanently constantly

Post by TheyCallMeTim13 »

If you use the module with other code make sure to remove the return else it will stop execution there.
To make a blacklist, you want to add a table, and use a loop to iterate through it and check for the description. Or you could use the description as the table key with a value of true, and check for that.

Try this:

Code: Select all

local format = string.format
local strE = string.empty or STRING_EMPTY or ''
local t = translate
if AddressList == nil then
	AddressList = getAddressList()
end
if MainForm == nil then
	MainForm = getMainForm()
end


if getCEVersion == nil or getCEVersion() < 6.5 then
	messageDialog('It is recommended to use at least Cheat Engine 6.7! (Your Version: '..getCEVersion()..')', mtError, mbOK)
end

errorOnLookupFailure(false)
setGlobalDelayBetweenHotkeyActivation(200)
DefaultProccessName = "pcsx2.exe"
strings_add(getAutoAttachList(), DefaultProccessName)

PRIVATETABLE, SWITCHSUPPORT = true, false

function cycleFullCompact(sender,force)
	local state = not(compactmenuitem.Caption == 'Compact View Mode')
	if force~=nil then state = not force end
	compactmenuitem.Caption = state and 'Compact View Mode' or 'Full View Mode'
	getMainForm().Splitter1.Visible = state
	getMainForm().Panel4.Visible = state
	getMainForm().Panel5.Visible = state
end

function addCompactMenu()
	if compactmenualreadyexists then return end
	local parent = getMainForm().Menu.Items
	compactmenuitem = createMenuItem(parent); parent.add(compactmenuitem)
	compactmenuitem.Caption = 'Compact View Mode'
	compactmenuitem.OnClick = cycleFullCompact
	compactmenualreadyexists = 'yes'
end
addCompactMenu()
cycleFullCompact(nil, true)


----
--
---- Logger
	local Logger = {
		LEVELS = {
			OFF = 0, 
			FATAL = 1, 
			ERROR = 2, 
			WARN = 3, 
			INFO = 4, 
			DEBUG = 5, 
			TRACE = 6
		}, 
		Level = 0,
	}
	for k, v in pairs(Logger.LEVELS) do
		Logger[k:lower()] = function( ... ) return end
		Logger[k:lower() .. 'f'] = function( ... ) return end
		-- Logger[k:lower()] = function(msg, ex) return print(msg, ex) end
		-- Logger[k:lower() .. 'f'] = function(msg, ... ) return print(string.format(msg, ... )) end
	end

--
---- Helpers
	local function split(s, delimiter)
		result = {}
		for match in (s .. delimiter):gmatch('(.-)' .. delimiter) do
			table.insert(result, match)
		end
		return result
	end
	local function interp(s, tbl)
		if s == nil then return end
		return (s:gsub('($%b{})', function(w) return tbl[w:sub(3, -2)] or w end))
	end


--
---- I2CETState
I2CETState = { 
	--
	---- Settings
	DefaultState = 'default', 
	SaveFileName = 'I2CETState.${StateName}.txt', 
	UseMemoryRecordDescriptions = false, 
	LineEnd = '\n', 
	DisableBeforeLoad = true, 
	PrintStatus = false, --true, 
	SaveValueMatch = 'AUTO SET:',
	LineDelimiter = '<SEP>',
	ScriptID = 'I2CETStateSCRIPTID',
	BlackList = {
		['_[  I2CETState  ]_'] = true,
		['_[  Save Table State  ]_'] = true,
		['_[  Load Table State  ]_'] = true,
	},
}


function I2CETState.saveTableState(stateName)
	if not inMainThread() then
		synchronize(function(thread)
			I2CETState.saveTableState(stateName)
		end)
		return
	end
	Logger.trace()
	if I2CETState.PrintStatus and Logger.Level <= Logger.LEVELS.WARN then
		getLuaEngine().show()
	end
	if I2CETState.PrintStatus and Logger.Level <= Logger.LEVELS.WARN then
		print(format('Saving Table State:  %s', stateName))
	end
	local le = I2CETState.LineEnd
	local ld = I2CETState.LineDelimiter
	local sid = I2CETState.ScriptID
	local svm = I2CETState.SaveValueMatch
	if stateName == nil then
		stateName = I2CETState.DefaultState
	end
	local fileName = interp(I2CETState.SaveFileName, { StateName = stateName } )
	Logger.debugf('Using state file name: "%s"', fileName)
	local fileStr = strE
	for i = 0, AddressList.Count - 1 do
		local mr = AddressList.getMemoryRecord(i)
		if I2CETState.BlackList[mr.Description] ~= true
		and mr.Description:sub(0, 16) ~= 'Load Table State'
		and mr.Description:sub(0, 16) ~= 'Save Table State' then
			local id = tostring(mr.ID)
			if I2CETState.UseMemoryRecordDescriptions then
				id = mr.Description
			end
			if mr.Type == vtAutoAssembler and mr.Active then
				Logger.debugf('Saving script state: %d, %d, "%s"', mr.Index, mr.ID, mr.Description)
				fileStr = fileStr..id..ld..sid..ld..tostring(mr.Active)..le
			elseif mr.Description:sub(0, #svm) == svm and mr.Value ~= '??' then
				Logger.debugf('Saving value: %d, %d, "%s", %s', mr.Index, mr.ID, mr.Description, mr.Value)
				fileStr = fileStr..id..ld..mr.Value..ld..tostring(mr.Active)..le
			end
		end
	end
	local f, err = io.open(fileName, 'w')
	if err then
		Logger.errorf('The file could not be opened, "%s", %s', fileName, err)
	elseif f and not err then
		f:write(fileStr)
		f:close()
	end
end
saveTableState = I2CETState.saveTableState


function I2CETState.loadTableState(stateName)
	if not inMainThread() then
		synchronize(function(thread)
			I2CETState.loadTableState(stateName)
		end)
		return
	end
	Logger.trace()
	if I2CETState.PrintStatus and Logger.Level <= Logger.LEVELS.WARN then
		getLuaEngine().show()
	end
	if I2CETState.PrintStatus and Logger.Level <= Logger.LEVELS.WARN then
		print(format('Setting Table State:  %s', stateName))
	end
	local le = I2CETState.LineEnd
	local ld = I2CETState.LineDelimiter
	local sid = I2CETState.ScriptID
	local svm = I2CETState.SaveValueMatch
	if stateName == nil then
		stateName = I2CETState.DefaultState
	end
	local fileName = interp(I2CETState.SaveFileName, { StateName = stateName } )
	Logger.debugf('Using state file name: "%s"', fileName)
	local fileStr = nil
	local f, err = io.open(fileName, 'r')
	if err then
		Logger.infof('The local file could not be opened, "%s", %s', fileName, err)
		local tableFile = findTableFile(fileName)
		if tableFile == nil then
			Logger.warnf('file not found, "%s"', fileName)
			return
		end
		local stream = tableFile.getData()
		local bytes = stream.read(stream.Size)
		for i = 1, #bytes do
			if fileStr == nil then
				fileStr = strE
			end
			fileStr = fileStr .. string.char(bytes[i])
		end
	elseif f and not err then
		fileStr = f:read('*all')
		f:close()
	else
		Logger.errorf('The file could not be opened, "%s"', fileName)
	end
	if I2CETState.DisableBeforeLoad then
		for i = AddressList.Count - 1, 0, -1 do
			local mr = AddressList.getMemoryRecord(i)
			if I2CETState.BlackList[mr.Description] ~= true
			and mr.Description:sub(0, 16) ~= 'Load Table State'
			and mr.Description:sub(0, 16) ~= 'Save Table State' then
				if mr.Active then
					Logger.infof('Disabling memory record: %d, %d, "%s"', mr.Index, mr.ID, mr.Description)
					if I2CETState.PrintStatus and Logger.Level <= Logger.LEVELS.WARN then
						print(format('Disabling:  %s', mr.Description))
					end
					mr.Active = false
					while mr.Async and mr.AsyncProcessing do
						checkSynchronize()
					end
					sleep(0)
				end
			end
		end
		sleep(0)
	end
	if fileStr == nil then
		Logger.info('File string was nil')
		return
	end
	local lines = split(fileStr, I2CETState.LineEnd)
	for i, v in ipairs(lines) do
		if v ~= nil and v ~= strE then
			local data = split(v, I2CETState.LineDelimiter)
			local mr = nil
			if I2CETState.UseMemoryRecordDescriptions then
				mr = AddressList.getMemoryRecordByDescription(data[1])
			else
				mr = AddressList.getMemoryRecordByID(tonumber(data[1]))
			end
			if mr ~= nil then
				if mr.Type == vtAutoAssembler and mr.Active == false
				and data[2] == sid and data[3] == tostring(true) then
					Logger.infof('Enabling memory record: %d, %d, "%s"', mr.Index, mr.ID, mr.Description)
					if I2CETState.PrintStatus and Logger.Level <= Logger.LEVELS.WARN then
						print(format('Enabling:  "%s"', mr.Description))
					end
					mr.Active = true
					while mr.Async and mr.AsyncProcessing do
						checkSynchronize()
					end
					sleep(0)
				elseif mr.Type ~= vtAutoAssembler and mr.Description:sub(0, #svm) == svm then
					if mr.Value == '??' then
						Logger.warnf('Memory record value not set: %d, %d, "%s", "%s"', mr.Index, mr.ID, mr.Description, mr.Value)
						if I2CETState.PrintStatus and Logger.Level <= Logger.LEVELS.WARN then
							print(format('Memory record value not set:  "%s", "%s"', mr.Description, mr.Value))
						end
					else
						Logger.infof('Setting memory record: %d, %d, "%s", %s, %s', mr.Index, mr.ID, mr.Description, data[1], data[2])
						if I2CETState.PrintStatus and Logger.Level <= Logger.LEVELS.WARN then
							print(format('Setting:  "%s", %s', mr.Description, data[2]))
						end
						mr.Value = data[2]
						if data[3] == tostring(true) then
							mr.Active = true
						end
					end
				end
			else
				Logger.errorf('Memory record not found: "%s", "%s", "%s"', data[1], data[2], v)
			end
		end
	end
	if I2CETState.PrintStatus and Logger.Level <= Logger.LEVELS.WARN then
		print(format('Table State Set:  %s', stateName))
		getLuaEngine().hide()
	end
end
loadTableState = I2CETState.loadTableState
----


PROCESS_NAME = 'pcsx2.exe'
--------
-------- Auto Attach
--------
local autoAttachTimer = nil ---- variable to hold timer object
local autoAttachTimerInterval = 100 ---- Timer intervals are in milliseconds
local autoAttachTimerTicks = 0 ---- variable to count number of times the timer has run
local autoAttachTimerTickMax = 5000 ---- Set to zero to disable ticks max
local function autoAttachTimer_tick(timer) ---- Timer tick call back
	---- Destroy timer if max ticks is reached
	if autoAttachTimerTickMax > 0 and autoAttachTimerTicks >= autoAttachTimerTickMax then
		timer.destroy()
	end
	---- Check if process is running
	if getProcessIDFromProcessName(PROCESS_NAME) ~= nil then
		timer.destroy() ---- Destroy timer
		openProcess(PROCESS_NAME) ---- Open the process
		-- getAddressList().getMemoryRecordByDescription("max jump everywhere - change value to 60)").active=true
		--
		---- Just a way to do this with the NameList,
		----     thus you can just add to the list to make it work with other memory records.
		
	end
	autoAttachTimerTicks = autoAttachTimerTicks + 1 ---- Increase ticks
end
autoAttachTimer = createTimer(getMainForm()) ---- Create timer with the main form as it's parent
autoAttachTimer.Interval = autoAttachTimerInterval ---- Set timer interval
autoAttachTimer.OnTimer = autoAttachTimer_tick ---- Set timer tick call back
I move the setup variables to the top of the script and since you never used controlMainForm so I removed it. And you can remove the loop in the auto attach timer that iterates through the name list since it's not needed anymore. Plus you don't want to just set AddressList because in newer versions of CE it and MainForm are constants set by CE. The reason I have it check for nil then set those is to make it compatible with older CE versions. So now it has a black list.

And you can use this at the start of any script you want to blacklist, just put this in the enable section. And it will not effect that script when loading or saving.

Code: Select all

{$lua}
I2CETState.BlackList[memrec.Description] = true
{$asm}
And just to note any script that starts with "Load Table State" or "Save Table State" will be ignored as well.

EDIT: And you can use these to save different states and load them, just paste this to the address list. So long as you keep the "Save/Load Table State" you can rename those scripts and move them where you'd like. If you change the main one ("_[ I2CETState ]_") just make sure you add it to the blacklist, I'd just change that entry in the blacklist of the main code, since it'd likely be what you want to use regularly.

Code: Select all

<?xml version="1.0" encoding="utf-8"?>
<CheatTable>
  <CheatEntries>
    <CheatEntry>
      <ID>53</ID>
      <Description>"_[  I2CETState  ]_"</Description>
      <Options moHideChildren="1"/>
      <LastState Value="" Activated="1" RealAddress="00000000"/>
      <GroupHeader>1</GroupHeader>
      <CheatEntries>
        <CheatEntry>
          <ID>54</ID>
          <Description>"_[  Save Table State  ]_"</Description>
          <Options moHideChildren="1"/>
          <LastState Value="" RealAddress="00000000"/>
          <GroupHeader>1</GroupHeader>
          <CheatEntries>
            <CheatEntry>
              <ID>55</ID>
              <Description>"Save Table State : None  ()-&gt;"</Description>
              <LastState/>
              <Color>008000</Color>
              <VariableType>Auto Assembler Script</VariableType>
              <AssemblerScript>{$lua}
------------------------------ ENABLE ------------------------------
[ENABLE]
if syntaxcheck then return end
I2CETState.saveTableState('none')
if type(mrAutoDisable) == 'function' then
	mrAutoDisable(memrec.ID)
end
------------------------------ DISABLE ------------------------------
[DISABLE]
</AssemblerScript>
            </CheatEntry>
            <CheatEntry>
              <ID>56</ID>
              <Description>"Save Table State : Default  ()-&gt;"</Description>
              <LastState/>
              <Color>008000</Color>
              <VariableType>Auto Assembler Script</VariableType>
              <AssemblerScript>{$lua}
------------------------------ ENABLE ------------------------------
[ENABLE]
if syntaxcheck then return end
I2CETState.saveTableState('default')
if type(mrAutoDisable) == 'function' then
	mrAutoDisable(memrec.ID)
end
------------------------------ DISABLE ------------------------------
[DISABLE]
</AssemblerScript>
            </CheatEntry>
            <CheatEntry>
              <ID>57</ID>
              <Description>"Save Table State : Casual  ()-&gt;"</Description>
              <LastState/>
              <Color>008000</Color>
              <VariableType>Auto Assembler Script</VariableType>
              <AssemblerScript>{$lua}
------------------------------ ENABLE ------------------------------
[ENABLE]
if syntaxcheck then return end
I2CETState.saveTableState('casual')
if type(mrAutoDisable) == 'function' then
	mrAutoDisable(memrec.ID)
end
------------------------------ DISABLE ------------------------------
[DISABLE]
</AssemblerScript>
            </CheatEntry>
            <CheatEntry>
              <ID>58</ID>
              <Description>"Save Table State : Full  ()-&gt;"</Description>
              <LastState/>
              <Color>008000</Color>
              <VariableType>Auto Assembler Script</VariableType>
              <AssemblerScript>{$lua}
------------------------------ ENABLE ------------------------------
[ENABLE]
if syntaxcheck then return end
I2CETState.saveTableState('full')
if type(mrAutoDisable) == 'function' then
	mrAutoDisable(memrec.ID)
end
------------------------------ DISABLE ------------------------------
[DISABLE]
</AssemblerScript>
            </CheatEntry>
            <CheatEntry>
              <ID>59</ID>
              <Description>"Save Table State : Test  ()-&gt;"</Description>
              <LastState/>
              <Color>008000</Color>
              <VariableType>Auto Assembler Script</VariableType>
              <AssemblerScript>{$lua}
------------------------------ ENABLE ------------------------------
[ENABLE]
if syntaxcheck then return end
I2CETState.saveTableState('test')
if type(mrAutoDisable) == 'function' then
	mrAutoDisable(memrec.ID)
end
------------------------------ DISABLE ------------------------------
[DISABLE]
</AssemblerScript>
            </CheatEntry>
          </CheatEntries>
        </CheatEntry>
        <CheatEntry>
          <ID>60</ID>
          <Description>"_[  Load Table State  ]_"</Description>
          <Options moHideChildren="1"/>
          <LastState Value="" RealAddress="00000000"/>
          <GroupHeader>1</GroupHeader>
          <CheatEntries>
            <CheatEntry>
              <ID>61</ID>
              <Description>"Load Table State : None  ()-&gt;"</Description>
              <LastState/>
              <Color>008000</Color>
              <VariableType>Auto Assembler Script</VariableType>
              <AssemblerScript>{$lua}
------------------------------ ENABLE ------------------------------
[ENABLE]
if syntaxcheck then return end
I2CETState.loadTableState('none')
if type(mrAutoDisable) == 'function' then
	mrAutoDisable(memrec.ID)
end
------------------------------ DISABLE ------------------------------
[DISABLE]
</AssemblerScript>
            </CheatEntry>
            <CheatEntry>
              <ID>62</ID>
              <Description>"Load Table State : Default  ()-&gt;"</Description>
              <LastState/>
              <Color>008000</Color>
              <VariableType>Auto Assembler Script</VariableType>
              <AssemblerScript>{$lua}
------------------------------ ENABLE ------------------------------
[ENABLE]
if syntaxcheck then return end
I2CETState.loadTableState('default')
if type(mrAutoDisable) == 'function' then
	mrAutoDisable(memrec.ID)
end
------------------------------ DISABLE ------------------------------
[DISABLE]
</AssemblerScript>
            </CheatEntry>
            <CheatEntry>
              <ID>63</ID>
              <Description>"Load Table State : Casual  ()-&gt;"</Description>
              <LastState/>
              <Color>008000</Color>
              <VariableType>Auto Assembler Script</VariableType>
              <AssemblerScript>{$lua}
------------------------------ ENABLE ------------------------------
[ENABLE]
if syntaxcheck then return end
I2CETState.loadTableState('casual')
if type(mrAutoDisable) == 'function' then
	mrAutoDisable(memrec.ID)
end
------------------------------ DISABLE ------------------------------
[DISABLE]
</AssemblerScript>
            </CheatEntry>
            <CheatEntry>
              <ID>64</ID>
              <Description>"Load Table State : Full  ()-&gt;"</Description>
              <LastState/>
              <Color>008000</Color>
              <VariableType>Auto Assembler Script</VariableType>
              <AssemblerScript>{$lua}
------------------------------ ENABLE ------------------------------
[ENABLE]
if syntaxcheck then return end
I2CETState.loadTableState('full')
if type(mrAutoDisable) == 'function' then
	mrAutoDisable(memrec.ID)
end
------------------------------ DISABLE ------------------------------
[DISABLE]
</AssemblerScript>
            </CheatEntry>
            <CheatEntry>
              <ID>65</ID>
              <Description>"Load Table State : Test  ()-&gt;"</Description>
              <LastState/>
              <Color>008000</Color>
              <VariableType>Auto Assembler Script</VariableType>
              <AssemblerScript>{$lua}
------------------------------ ENABLE ------------------------------
[ENABLE]
if syntaxcheck then return end
I2CETState.loadTableState('test')
if type(mrAutoDisable) == 'function' then
	mrAutoDisable(memrec.ID)
end
------------------------------ DISABLE ------------------------------
[DISABLE]
</AssemblerScript>
            </CheatEntry>
          </CheatEntries>
        </CheatEntry>
      </CheatEntries>
    </CheatEntry>
  </CheatEntries>
</CheatTable>

User avatar
dreamcactus
Expert Cheater
Expert Cheater
Posts: 108
Joined: Sat Jul 06, 2019 12:21 pm
Reputation: 0

Re: Need Help on my Lua Script to force a certain Value permanently constantly

Post by dreamcactus »

uhhhh...wow my head...its about to freakin explode here lol, serious tho ...i stopped thinking there for a sec....after running it trough my brain cells ...the few i have lols ...again, i figured ...you DONT need a blacklist, hence why ive deleted previous post...since your setup simply will save the CTs current state aka cheats youve enabled ...cheats youve changed values and freeze and forces/locks said value set and cheats that are disabled aka not checked ...so no need for a blacklist , am i right? also please is possible post full script ...im not good with bits and bobs lol aka the full thing so i can just copy and paste and test....thanks

User avatar
TheyCallMeTim13
Administration
Administration
Posts: 1660
Joined: Fri Mar 03, 2017 12:31 am
Reputation: 876

Re: Need Help on my Lua Script to force a certain Value permanently constantly

Post by TheyCallMeTim13 »

dreamcactus wrote:
Fri May 14, 2021 1:17 pm
uhhhh...wow my head...its about to freakin explode here lol, serious tho ...i stopped thinking there for a sec....after running it trough my brain cells ...the few i have lols ...again, i figured ...you DONT need a blacklist, hence why ive deleted previous post...since your setup simply will save the CTs current state aka cheats youve enabled ...cheats youve changed values and freeze and forces/locks said value set and cheats that are disabled aka not checked ...so no need for a blacklist , am i right? also please is possible post full script ...im not good with bits and bobs lol aka the full thing so i can just copy and paste and test....thanks
Yeah the only thing you need to blacklist are auto assembler scripts you want it to ignore. But it doesn't detect changes, it just looks for enabled auto assembler scripts; and any descriptions that starts with "AUTO SET:" will be treated as a value to save and load.

So the first script is the lua script, you'll want to add that to the table lua script. And the second one is just a snippet you add to any auto assembler scripts you want to blacklist, it just uses the memrec variable that CE passes to auto assembler table scripts. Then the third one is just a collection of stuff I add to my tables that uses the I2CETState module, so just copy that and paste it into the address list of your table and it will add some memory records (headers and scripts) that make saving a state and load a state easier.

User avatar
dreamcactus
Expert Cheater
Expert Cheater
Posts: 108
Joined: Sat Jul 06, 2019 12:21 pm
Reputation: 0

Re: Need Help on my Lua Script to force a certain Value permanently constantly

Post by dreamcactus »

ok so , im still stumped ...you able to show this on an example? , heres a CT to work with for example , im a visual kinda dude aka a youtube video would be the best tbh, anyhow heres an example you can use>

[Link]

User avatar
dreamcactus
Expert Cheater
Expert Cheater
Posts: 108
Joined: Sat Jul 06, 2019 12:21 pm
Reputation: 0

Re: Need Help on my Lua Script to force a certain Value permanently constantly

Post by dreamcactus »

game also loves to change Values , hence the request to make sure that Values i Set are frozen aka cant be changed by game not just saved and autoloaded and enabled or disabled ...depending on if i enabled or disabled said cheat before closing CT

User avatar
dreamcactus
Expert Cheater
Expert Cheater
Posts: 108
Joined: Sat Jul 06, 2019 12:21 pm
Reputation: 0

Re: Need Help on my Lua Script to force a certain Value permanently constantly

Post by dreamcactus »

well ...dont work , it wont autosave cheats ive enabled , nor does it save and freeze its values set, and on CT restart to have said cheats autoenabled and Values set/freeze/forced , even tho ive put it like this as a quick test>
in Description as you said in order for values to save, freeze/forced

AUTO SET: max jump everywhere - change value to 60

this is the current lua script>

Code: Select all

local format = string.format
local strE = string.empty or STRING_EMPTY or ''
local t = translate
if AddressList == nil then
	AddressList = getAddressList()
end
if MainForm == nil then
	MainForm = getMainForm()
end


if getCEVersion == nil or getCEVersion() < 6.5 then
	messageDialog('It is recommended to use at least Cheat Engine 6.7! (Your Version: '..getCEVersion()..')', mtError, mbOK)
end

errorOnLookupFailure(false)
setGlobalDelayBetweenHotkeyActivation(200)
DefaultProccessName = "pcsx2.exe"
strings_add(getAutoAttachList(), DefaultProccessName)

PRIVATETABLE, SWITCHSUPPORT = true, false

function cycleFullCompact(sender,force)
	local state = not(compactmenuitem.Caption == 'Compact View Mode')
	if force~=nil then state = not force end
	compactmenuitem.Caption = state and 'Compact View Mode' or 'Full View Mode'
	getMainForm().Splitter1.Visible = state
	getMainForm().Panel4.Visible = state
	getMainForm().Panel5.Visible = state
end

function addCompactMenu()
	if compactmenualreadyexists then return end
	local parent = getMainForm().Menu.Items
	compactmenuitem = createMenuItem(parent); parent.add(compactmenuitem)
	compactmenuitem.Caption = 'Compact View Mode'
	compactmenuitem.OnClick = cycleFullCompact
	compactmenualreadyexists = 'yes'
end
addCompactMenu()
cycleFullCompact(nil, true)


----
--
---- Logger
	local Logger = {
		LEVELS = {
			OFF = 0, 
			FATAL = 1, 
			ERROR = 2, 
			WARN = 3, 
			INFO = 4, 
			DEBUG = 5, 
			TRACE = 6
		}, 
		Level = 0,
	}
	for k, v in pairs(Logger.LEVELS) do
		Logger[k:lower()] = function( ... ) return end
		Logger[k:lower() .. 'f'] = function( ... ) return end
		-- Logger[k:lower()] = function(msg, ex) return print(msg, ex) end
		-- Logger[k:lower() .. 'f'] = function(msg, ... ) return print(string.format(msg, ... )) end
	end

--
---- Helpers
	local function split(s, delimiter)
		result = {}
		for match in (s .. delimiter):gmatch('(.-)' .. delimiter) do
			table.insert(result, match)
		end
		return result
	end
	local function interp(s, tbl)
		if s == nil then return end
		return (s:gsub('($%b{})', function(w) return tbl[w:sub(3, -2)] or w end))
	end


--
---- I2CETState
I2CETState = { 
	--
	---- Settings
	DefaultState = 'default', 
	SaveFileName = 'I2CETState.${StateName}.txt', 
	UseMemoryRecordDescriptions = false, 
	LineEnd = '\n', 
	DisableBeforeLoad = true, 
	PrintStatus = false, --true, 
	SaveValueMatch = 'AUTO SET:',
	LineDelimiter = '',
	ScriptID = 'I2CETStateSCRIPTID',
	BlackList = {
		['_[  I2CETState  ]_'] = true,
		['_[  Save Table State  ]_'] = true,
		['_[  Load Table State  ]_'] = true,
	},
}


function I2CETState.saveTableState(stateName)
	if not inMainThread() then
		synchronize(function(thread)
			I2CETState.saveTableState(stateName)
		end)
		return
	end
	Logger.trace()
	if I2CETState.PrintStatus and Logger.Level <= Logger.LEVELS.WARN then
		getLuaEngine().show()
	end
	if I2CETState.PrintStatus and Logger.Level <= Logger.LEVELS.WARN then
		print(format('Saving Table State:  %s', stateName))
	end
	local le = I2CETState.LineEnd
	local ld = I2CETState.LineDelimiter
	local sid = I2CETState.ScriptID
	local svm = I2CETState.SaveValueMatch
	if stateName == nil then
		stateName = I2CETState.DefaultState
	end
	local fileName = interp(I2CETState.SaveFileName, { StateName = stateName } )
	Logger.debugf('Using state file name: "%s"', fileName)
	local fileStr = strE
	for i = 0, AddressList.Count - 1 do
		local mr = AddressList.getMemoryRecord(i)
		if I2CETState.BlackList[mr.Description] ~= true
		and mr.Description:sub(0, 16) ~= 'Load Table State'
		and mr.Description:sub(0, 16) ~= 'Save Table State' then
			local id = tostring(mr.ID)
			if I2CETState.UseMemoryRecordDescriptions then
				id = mr.Description
			end
			if mr.Type == vtAutoAssembler and mr.Active then
				Logger.debugf('Saving script state: %d, %d, "%s"', mr.Index, mr.ID, mr.Description)
				fileStr = fileStr..id..ld..sid..ld..tostring(mr.Active)..le
			elseif mr.Description:sub(0, #svm) == svm and mr.Value ~= '??' then
				Logger.debugf('Saving value: %d, %d, "%s", %s', mr.Index, mr.ID, mr.Description, mr.Value)
				fileStr = fileStr..id..ld..mr.Value..ld..tostring(mr.Active)..le
			end
		end
	end
	local f, err = io.open(fileName, 'w')
	if err then
		Logger.errorf('The file could not be opened, "%s", %s', fileName, err)
	elseif f and not err then
		f:write(fileStr)
		f:close()
	end
end
saveTableState = I2CETState.saveTableState


function I2CETState.loadTableState(stateName)
	if not inMainThread() then
		synchronize(function(thread)
			I2CETState.loadTableState(stateName)
		end)
		return
	end
	Logger.trace()
	if I2CETState.PrintStatus and Logger.Level <= Logger.LEVELS.WARN then
		getLuaEngine().show()
	end
	if I2CETState.PrintStatus and Logger.Level <= Logger.LEVELS.WARN then
		print(format('Setting Table State:  %s', stateName))
	end
	local le = I2CETState.LineEnd
	local ld = I2CETState.LineDelimiter
	local sid = I2CETState.ScriptID
	local svm = I2CETState.SaveValueMatch
	if stateName == nil then
		stateName = I2CETState.DefaultState
	end
	local fileName = interp(I2CETState.SaveFileName, { StateName = stateName } )
	Logger.debugf('Using state file name: "%s"', fileName)
	local fileStr = nil
	local f, err = io.open(fileName, 'r')
	if err then
		Logger.infof('The local file could not be opened, "%s", %s', fileName, err)
		local tableFile = findTableFile(fileName)
		if tableFile == nil then
			Logger.warnf('file not found, "%s"', fileName)
			return
		end
		local stream = tableFile.getData()
		local bytes = stream.read(stream.Size)
		for i = 1, #bytes do
			if fileStr == nil then
				fileStr = strE
			end
			fileStr = fileStr .. string.char(bytes[i])
		end
	elseif f and not err then
		fileStr = f:read('*all')
		f:close()
	else
		Logger.errorf('The file could not be opened, "%s"', fileName)
	end
	if I2CETState.DisableBeforeLoad then
		for i = AddressList.Count - 1, 0, -1 do
			local mr = AddressList.getMemoryRecord(i)
			if I2CETState.BlackList[mr.Description] ~= true
			and mr.Description:sub(0, 16) ~= 'Load Table State'
			and mr.Description:sub(0, 16) ~= 'Save Table State' then
				if mr.Active then
					Logger.infof('Disabling memory record: %d, %d, "%s"', mr.Index, mr.ID, mr.Description)
					if I2CETState.PrintStatus and Logger.Level <= Logger.LEVELS.WARN then
						print(format('Disabling:  %s', mr.Description))
					end
					mr.Active = false
					while mr.Async and mr.AsyncProcessing do
						checkSynchronize()
					end
					sleep(0)
				end
			end
		end
		sleep(0)
	end
	if fileStr == nil then
		Logger.info('File string was nil')
		return
	end
	local lines = split(fileStr, I2CETState.LineEnd)
	for i, v in ipairs(lines) do
		if v ~= nil and v ~= strE then
			local data = split(v, I2CETState.LineDelimiter)
			local mr = nil
			if I2CETState.UseMemoryRecordDescriptions then
				mr = AddressList.getMemoryRecordByDescription(data[1])
			else
				mr = AddressList.getMemoryRecordByID(tonumber(data[1]))
			end
			if mr ~= nil then
				if mr.Type == vtAutoAssembler and mr.Active == false
				and data[2] == sid and data[3] == tostring(true) then
					Logger.infof('Enabling memory record: %d, %d, "%s"', mr.Index, mr.ID, mr.Description)
					if I2CETState.PrintStatus and Logger.Level <= Logger.LEVELS.WARN then
						print(format('Enabling:  "%s"', mr.Description))
					end
					mr.Active = true
					while mr.Async and mr.AsyncProcessing do
						checkSynchronize()
					end
					sleep(0)
				elseif mr.Type ~= vtAutoAssembler and mr.Description:sub(0, #svm) == svm then
					if mr.Value == '??' then
						Logger.warnf('Memory record value not set: %d, %d, "%s", "%s"', mr.Index, mr.ID, mr.Description, mr.Value)
						if I2CETState.PrintStatus and Logger.Level <= Logger.LEVELS.WARN then
							print(format('Memory record value not set:  "%s", "%s"', mr.Description, mr.Value))
						end
					else
						Logger.infof('Setting memory record: %d, %d, "%s", %s, %s', mr.Index, mr.ID, mr.Description, data[1], data[2])
						if I2CETState.PrintStatus and Logger.Level <= Logger.LEVELS.WARN then
							print(format('Setting:  "%s", %s', mr.Description, data[2]))
						end
						mr.Value = data[2]
						if data[3] == tostring(true) then
							mr.Active = true
						end
					end
				end
			else
				Logger.errorf('Memory record not found: "%s", "%s", "%s"', data[1], data[2], v)
			end
		end
	end
	if I2CETState.PrintStatus and Logger.Level <= Logger.LEVELS.WARN then
		print(format('Table State Set:  %s', stateName))
		getLuaEngine().hide()
	end
end
loadTableState = I2CETState.loadTableState
----


PROCESS_NAME = 'pcsx2.exe'
--------
-------- Auto Attach
--------
local autoAttachTimer = nil ---- variable to hold timer object
local autoAttachTimerInterval = 100 ---- Timer intervals are in milliseconds
local autoAttachTimerTicks = 0 ---- variable to count number of times the timer has run
local autoAttachTimerTickMax = 5000 ---- Set to zero to disable ticks max
local function autoAttachTimer_tick(timer) ---- Timer tick call back
	---- Destroy timer if max ticks is reached
	if autoAttachTimerTickMax > 0 and autoAttachTimerTicks >= autoAttachTimerTickMax then
		timer.destroy()
	end
	---- Check if process is running
	if getProcessIDFromProcessName(PROCESS_NAME) ~= nil then
		timer.destroy() ---- Destroy timer
		openProcess(PROCESS_NAME) ---- Open the process
		-- getAddressList().getMemoryRecordByDescription("max jump everywhere - change value to 60)").active=true
		--
		---- Just a way to do this with the NameList,
		----     thus you can just add to the list to make it work with other memory records.
		
	end
	autoAttachTimerTicks = autoAttachTimerTicks + 1 ---- Increase ticks
end
autoAttachTimer = createTimer(getMainForm()) ---- Create timer with the main form as it's parent
autoAttachTimer.Interval = autoAttachTimerInterval ---- Set timer interval
autoAttachTimer.OnTimer = autoAttachTimer_tick ---- Set timer tick call back

User avatar
dreamcactus
Expert Cheater
Expert Cheater
Posts: 108
Joined: Sat Jul 06, 2019 12:21 pm
Reputation: 0

Re: Need Help on my Lua Script to force a certain Value permanently constantly

Post by dreamcactus »

btw do i still have to now set cheats in the getAddressList?
since i still have that one cheat as test in it

-- getAddressList().getMemoryRecordByDescription("max jump everywhere - change value to 60)").active=true

thought you said i dont have to do this no more?

User avatar
TheyCallMeTim13
Administration
Administration
Posts: 1660
Joined: Fri Mar 03, 2017 12:31 am
Reputation: 876

Re: Need Help on my Lua Script to force a certain Value permanently constantly

Post by TheyCallMeTim13 »

If it's a script you don't need to do anything with the description, if it's a value the description has to start with "AUTO SET:". And it doesn't run automatically, you have to call the functions (i.e.: "saveTableState" and "loadTableState").

User avatar
dreamcactus
Expert Cheater
Expert Cheater
Posts: 108
Joined: Sat Jul 06, 2019 12:21 pm
Reputation: 0

Re: Need Help on my Lua Script to force a certain Value permanently constantly

Post by dreamcactus »

well can we have it run automatically , since thats the entire aim to be able to have it autosave current settings and values and have them autoapply on fresh start of CT and also to make sure values entered are frozen


also this is the output when i enable save and load one of the profiles in I2CETState like for example full> 16560false

User avatar
TheyCallMeTim13
Administration
Administration
Posts: 1660
Joined: Fri Mar 03, 2017 12:31 am
Reputation: 876

Re: Need Help on my Lua Script to force a certain Value permanently constantly

Post by TheyCallMeTim13 »

You'd have to auto attach to the process, then wait for things to load. Then you could run the loadTableState function. And for an auto save you'd need to hook the CE forms on close function and call saveTableState before calling the original on close.

Try this table it's setup with the module in an assembler script. So you'd need to move it for the auto load/save thing. But you can use the "casual" state to load the table file before saving, see it that works.
Tutorial-x86_64.I2CETState.stripped.CT
(21.16 KiB) Downloaded 24 times

User avatar
dreamcactus
Expert Cheater
Expert Cheater
Posts: 108
Joined: Sat Jul 06, 2019 12:21 pm
Reputation: 0

Re: Need Help on my Lua Script to force a certain Value permanently constantly

Post by dreamcactus »

ill give that a check and get back atcha , thanks

p.s about the autoattach to process....isnt an issue as CE has that built in its settings...as you know , which i already use, also yes of course i never run CTs before the game isnt loaded , wouldnt make sense , i use a batch/vbs file to easy autolaunch game ....then trainers, CTs etc , which streamlines the entire process of only having to launch one shortcut and the rest runs invisible and autoexits all processes tied to game on game exit, for a more clean and unobtrusive experience, sure theres games where i alt+enter to change and modify CTs ...Trainers etc. to my liking , but where talking regular gaming sessions

Post Reply

Who is online

Users browsing this forum: No registered users