Supporter13
Supporter13

Reputation: 3

scilab local variables on different functions

so i have something like this i'm calling for fun3 which calls fun1. In fun1 the user inputs some text in variables a and b then fun2 makes use of it, but how do i link the local variables in the different functions and then bring them to fun3 to make use of them too, do i have to define them in the main program first?

i know i have to use the input and output arguments in the functions but i think i'm doing it wrong i left them empty so that someone help me complete them

FUNCTIONS

function [] = fun1 ()
    a=input("input is text")
    b=input("input is text")
end function

function [] = fun2()
    printf("a is b")
end function

function [] = fun3()
    fun1()
    fun2()
    disp(a)
    disp(b)
end function

MAIN PROGRAM

fun3()

Upvotes: 0

Views: 875

Answers (1)

spoorcc
spoorcc

Reputation: 2955

Welcome to the world of programming/SciLab. There are great tutorials such as these which can help you to get started. Find a list of others on the SciLab wiki.

To get to your question let's go through each function 1-by-1.

fun1

This function needs to ask the user for two strings a and b. I think you meant the inputs are strings so according to the input function docs, we should add "string" to the call. Also see the examples on the link. To make fun1 return these to string we put them in the output arguments of the function.

function [a,b] = fun1()
    a=input("input a is text: ", "string")
    b=input("input b is text: ", "string")
endfunction

fun2

Because you used printf, I'm assuming you would like to print a and b with some additional text. You can see some examples on using printf at the bottom of this page. To print them, we will need to know the value, so specify a and b as input parameters.

function [] = fun2(a,b)
    printf("a (%s) is b (%s)", a, b)
endfunction

fun3

In fun3 you want to call the function that get the user input called fun1 and whatever it returns, you want to send to fun2 which prints the two. Then you want to print the values again.

Notice that when using the functions, the names do not need to be the same as the names of the local variables.

function [] = fun3()
    [c,d] = fun1()
    fun2(c,d)
    disp(c)
    disp(d)
endfunction

answer to your question

Defining the variables in the main program makes them global. If you can avoid this, always avoid this. Always try to work with local variables only and use proper input and output variables as I showed above. This way you know every variable flowing in your function and out of your function within one glance. It makes testing your functions much easier. If you know a function works by trying all kinds of inputs and checking the outputs, you can forget about it and use it.

Also see why globals are bad. It is about c, but he makes some valid points.

finally

I would suggest to do some tutorials first, to get and understand the basic stuff.

Upvotes: 1

Related Questions