Page 1 of 1

Source code loading from .txt file :P

Posted: Mon Apr 13, 2015 7:41 pm
by likemau5
Hi, let's say i have source code for enemy saved in .txt file and need to load it to variable, and then run this code from that variable.

something like this:

function love.load()
monsterhp = 15
--want to load the .txt file contents here
end
function love.update(dt)
-- running txt contents here
end


Is it even possible? :D

Re: Source code loading from .txt file :P

Posted: Mon Apr 13, 2015 8:24 pm
by NCN
Make a .lua file for your enemy! Name it enemy.lua and you can use a require-command to use it in your main.lua:

Code: Select all

require("enemy")
You can define functions and variables in enemy.lua and use them by adding "enemy." without quotes in front of them in the main.lua. No need for txt-files here. If you look at some source code from other games, you can see that this is common practice. I suggest checking out http://stabyourself.net for some examples. The games in the sidebar are made with LÖVE and have the sources available.

Re: Source code loading from .txt file :P

Posted: Mon Apr 13, 2015 8:38 pm
by arampl
Sure. Look for loadfile() / loadstring() / dofile() Lua's functions.

Re: Source code loading from .txt file :P

Posted: Tue Apr 14, 2015 1:40 am
by I~=Spam
Do this:

Code: Select all

-- load file contents as a string
contents = love.filesystem.read("/path/to/file")

-- execute string
loadstring(contents) ()

-- use this if you want to "catch" any errors that are thrown when running this string of code
-- assert(loadstring(contents)) ()
This might also be of interest to you if you are running foreign untrusted lua code. ;)
For lua 5.1: http://lua-users.org/wiki/SandBoxes
For lua 5.1 and 5.2: http://lua-users.org/wiki/EnvironmentsTutorial
These might help too: http://stackoverflow.com/questions/1128 ... in-lua-5-2 http://stackoverflow.com/questions/1224 ... ua-sandbox

Re: Source code loading from .txt file :P

Posted: Tue Apr 14, 2015 12:40 pm
by likemau5
I~=Spam wrote:Do this:

Code: Select all

-- load file contents as a string
contents = love.filesystem.read("/path/to/file")

-- execute string
loadstring(contents) ()

-- use this if you want to "catch" any errors that are thrown when running this string of code
-- assert(loadstring(contents)) ()
This might also be of interest to you if you are running foreign untrusted lua code. ;)
For lua 5.1: http://lua-users.org/wiki/SandBoxes
For lua 5.1 and 5.2: http://lua-users.org/wiki/EnvironmentsTutorial
These might help too: http://stackoverflow.com/questions/1128 ... in-lua-5-2 http://stackoverflow.com/questions/1224 ... ua-sandbox

Thank You very much :) That's exaclty what i need!