Page 1 of 1

Isolating dofile() from love.* functions?

Posted: Wed Mar 18, 2020 7:38 pm
by Flamore
Let's say i've got a variable like "score" that equals zero. and if i dofile i want the dofile function to be only able to access variables from main.lua and not from the rest of the Love2d engine. I've saw setfenv but it isn't really that straight forward.

Re: Isolating dofile() from love.* functions?

Posted: Wed Mar 18, 2020 11:58 pm
by AuahDark
First, dofile doesn't really work in real scenarios. For your real solutions, you can use love.filesystem.load(file), setfenv the resulting function, and call it.

Re: Isolating dofile() from love.* functions?

Posted: Thu Mar 19, 2020 3:42 pm
by Flamore
AuahDark wrote: Wed Mar 18, 2020 11:58 pm First, dofile doesn't really work in real scenarios. For your real solutions, you can use love.filesystem.load(file), setfenv the resulting function, and call it.
Alright so i merged the example setfenv function with lua.filedropper

Code: Select all

-- EXECUTE CODE
function love.filedropped(file)
	local ext
	ext = file:getExtension( )
	if ext == "cart" then
		executelua(file:getFilename())
	else
		print("Filetype not supported")
	end
end
function executelua(fn)
  -- read and parse the file
  local func, err = love.filesystem.load(fn)
  if not func then
    -- syntax error
    return false, err
  end
  -- lock out the environment
  setfenv(func, {})
  -- execute
  return pcall(func)
end
then i drop the cart file with no output or input results.

Code: Select all

game_title = "RGB palette and input demo."
resizescreen(1)
function gamedraw()
	if up == true then setpixel(2,1,8,lcdt) else setpixel(2,1,2,lcdt) end
	if down == true then setpixel(2,3,8,lcdt) else setpixel(2,3,2,lcdt) end
	if left == true then setpixel(1,2,8,lcdt) else setpixel(1,2,2,lcdt) end
	if right == true then setpixel(3,2,8,lcdt) else setpixel(3,2,2,lcdt) end
	if fire == true then setpixel(4,4,8,lcdt) else setpixel(4,4,2,lcdt) end
	for i=0, 15 do
		setpixel(1,i-1,i,lcd)
	end
end
function gameupdate()
end
all the functions just set values to an array that is drawn like a virtual screen

Re: Isolating dofile() from love.* functions?

Posted: Fri Mar 20, 2020 1:27 pm
by AuahDark
For your example code, neither dofile and love.filesystem.load fits the scenario. You can first read all the contents, pass the file contents to "loadstring" function which returns same result as love.filesystem.load, setfenv the resulting function, then call it.