loading a file iff it exists

Discussion of Lua and LuaWML support, development, and ideas.

Moderators: Forum Moderators, Developers

loading a file iff it exists

Postby melinath » March 26th, 2011, 7:21 pm

Does anyone happen to know a technique for loading a file iff it exists? I've tried:

Code: Select all
pcall(wesnoth.require("blah.lua"))


but the "file does not exist" error still propagates and halts my code.
User avatar
melinath
 
Posts: 1298
Joined: May 20th, 2009, 7:42 am

Re: loading a file iff it exists

Postby Alarantalara » March 26th, 2011, 8:24 pm

pcall doesn't work that way, which is why you're having the problem. It needs a function as an argument to execute, not the result of the execution.

Staying with pcall, the correct way to use it is:
Code: Select all
pcall(function () wesnoth.require("blah.lua") end)


I've used an anonymous function to minimize the space taken, but the point is that you pass the name of a function but do not call it yourself. This means the function must have 0 arguments.
User avatar
Alarantalara
macOS Packager
 
Posts: 782
Joined: April 23rd, 2010, 8:17 pm
Location: Canada

Re: loading a file iff it exists

Postby melinath » March 26th, 2011, 9:35 pm

Hah... of course. Thanks. I swear I read the docs... :-p

Incidentally, though, pcall can take a function with args[1]. This is what I'm doing now (which works):

Code: Select all
pcall(wesnoth.require, "blah.lua")


[1] http://www.lua.org/manual/5.1/manual.html#pdf-pcall
User avatar
melinath
 
Posts: 1298
Joined: May 20th, 2009, 7:42 am

Re: loading a file iff it exists

Postby Alarantalara » March 26th, 2011, 9:38 pm

And now I've learned that pcall has variable argument lists. Excellent.
User avatar
Alarantalara
macOS Packager
 
Posts: 782
Joined: April 23rd, 2010, 8:17 pm
Location: Canada


Return to Lua Labs

Who is online

Users browsing this forum: No registered users and 1 guest