Jump to content



Photo

Reading The File


  • Please log in to reply
1 reply to this topic

#1 saeed511

saeed511

    Newbie

  • Members
  • Pip
  • 2 posts

Posted 23 September 2013 - 11:34 AM

hello
help me to read a file from other file .
please modify files below :

---- file2 (for cal file1)
ww=1
require "file1"
print(456*a)

----- file1
a=input("a ?")
if ww==1 then
return a
else print(3*a)
end


#2 MicroPro

MicroPro

    Casio Overlord

  • Deputy
  • PipPipPipPipPipPipPip
  • 640 posts
  • Gender:Male
  • Location:Iran

  • Calculators:
    Casio ClassPad 300

Posted 24 March 2014 - 11:05 AM

Hi. Late answer but I think it's worth it for future reference.

Note: your file1 has an if statement that returns a in its first clause but does not return anything in its else clause. I don't know what you actually meant but I assume you want to return 3*a there instead of just printing it.

Your Method (not recommended)
Note that if you want to modularize your project, your method is NOT the best way and many don't recommend it. require can't be used here, so let's try a different function: doscript.

---- file2 (for cal file1)
ww=1
a = doscript("file1", {ww=ww})
print(456*a)

----- file1
a=input("a ?")
if args.ww==1 then
return a
else
return 3*a
end

In file2 I used doscript instead of require and gave {ww=ww} as its second argument: This defines a table, which has a member called ww which refers to your original ww variable. In file1, I use args.ww to retrieve its value. (To make the doscript statement clear, if I had given { somename = ww } as the second argument, I would have used args.somename in file1).

Also, if you want to be able to use just ww instead of args.ww in your file1, add this to the top of file1:
for k,v in pairs(args) do
_G[k] = v
end
This will extract the variables from args and will put it in Lua's 'global table'.

Better, Correct Method
Correct method is to define function and use the export function:

---- file2 (for cal file1)
require("file1")
ww=1
a = GetInput(ww)
print(456*a)

----- file1
function GetInput(w)
a=input("a ?")
if w==1 then
return a
else
return 3*a
end
end
export { GetInput = GetInput }

Now file1 contains our user-defined function called GetInput which gets a parameter called w (formerly your ww). At the end of file1, we export the function with the syntax you see. In file2, we require file1 and have our GetInput function available and can use it.

This second method makes it clear and easy to pass and differentiate between input and output variables and is the way libraries are made in CPLua.
  • flyingfisch likes this


1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users