How to declare variables with a type in Lua - oop

Is it possible to create variables to be a specific type in Lua?
E.g. int x = 4
If this is not possible, is there at least some way to have a fake "type" shown before the variable so that anyone reading the code will know what type the variable is supposed to be?
E.g. function addInt(int x=4, int y=5), but x/y could still be any type of variable? I find it much easier to type the variable's type before it rather than putting a comment at above the function to let any readers know what type of variable it is supposed to be.
The sole reason I'm asking isn't to limit the variable to a specific data type, but simply to have the ability to put a data type before the variable, whether it does anything or not, to let the reader know what type of variable that it is supposed to be without getting an error.

You can do this using comments:
local x = 4 -- int
function addInt(x --[[int]],
y --[[int]] )
You can make the syntax a = int(5) from your other comment work using the following:
function int(a) return a end
function string(a) return a end
function dictionary(a) return a end
a = int(5)
b = string "hello, world!"
c = dictionary({foo = "hey"})
Still, this doesn't really offer any benefits over a comment.

The only way I can think of to do this, would be by creating a custom type in C.
Lua Integer type

No. But I understand your goal is to improve understanding when reading and writing functions calls.
Stating the expected data type of parameters adds only a little in terms of giving a specification for the function. Also, some function parameters are polymorphic, accepting a specific value, or a function or table from which to obtain the value for a context in which the function operates. See string.gsub, for example.
When reading a function call, the only thing known at the call site is the name of the variable or field whose value is being invoked as a function (sometimes read as the "name" of the function) and the expressions being passed as actual parameters. It is sometimes helpful to refactor parameter expressions into named local variables to add to the readability.
When writing a function call, the name of the function is key. The names of the formal parameters are also helpful. But still, names (like types) do not comprise much of a specification. The most help comes from embedded structured documentation used in conjunction with an IDE that infers the context of a name and performs content assistance and presentations of available documentation.
luadoc is one such a system of documentation. You can write luadoc for function you declare.
Eclipse Koneki LDT is one such an IDE. Due to the dynamic nature of Lua, it is a difficult problem so LDT is not always as helpful as one would like. (To be clear, LDT does not use luadoc; It evolved its own embedded documentation system.)

Related

Are dynamic types slower in Dart?

I have been wondering if dynamic types are slower in Dart.
Example given:
final dynamic example = "Example"
versus
final String example = "Example"
Yes, using dynamic typed variables in Dart is often slower than using variables typed with an actual type.
However, your example is not using dynamic as type, it is using type inference to infer the String type. That might cost a little extra at compile-time, but at run-time, your two code examples are completely identical. Both variables are typed as String.
A dynamic method invocation may be slower because the run-time system must add extra checks to ensure that the variable can do the things you are trying to do with it.
If you have int x = 2; print(x + 3); the run-time system knows that int has a + operator, and even knows what it is.
If you write dynamic x = 2; print(x + 3);, the run-time system must first check whether x has a + operator before it can call it, and find that operator's definition on the object before calling it. It might not always be slower, some cases optimize better than others, but it can never be faster.
Not all code is performance sensitive, and not all variables can be typed. If you have a variable that holds either a String or a List, and you want to know the length, just writing stringOrList.length is more convenient than stringOrList is String ? stringOrList.length : (stringOrList as List).length. It may be slower depending on the compiler and the target platform.
Well, in your first example (heh), example is inferred to be a type String, not dynamic, so how could it be slower? The style guide even recommends not adding redundant types to those variables that can be inferred correctly.

a middle approach between Dynamic Typing and Static Typing

I wanted to ask if anyone knows of a programming language where there is dynamic typing but the binding between a name and a type is permanent. Static typing guards your code from assigning a wrong value into a variable, but forces you to declare(and know) the type before compilation. Dynamic typing allows you to assign values with a different type to the same variable one after the other. What I was thinking is, it would be nice to have dynamic typing, but once the variable is bound, the first binding also determines the type of the variable.
For example, using python-like syntax, if I write by mistake:
persons = []
....
adam = Person("adam")
persons = adam #(instead of persons += [adam])
Then I want to get an error(either at runtime or during compilation if possible) because name was defined as a list, and cannot accept values of type Person.
Same thing if the type can not be resolved statically:
result = getData()
...
result = 10
Will generate a runtime error iff getData() did not return an integer.
I know you can hack a similar behavior with a wrapper class but it would be nice to have the option by default in the language as I don't see a good legitimate use for this flexibility in dynamic languages(except for inheritance, or overwriting a common default value such as null/None which could be permitted as special cases).

Passing parameters of varying Types

I am using a procedure which involves parameter passing and the parameter being passed is a variable. Because I have explicitly declared the data type of another parameter, I need to do the same for this one. What data type do I declare the parameter as if it is a variable?
Thanks
An example of what you are doing and what Types you are dealing with would have been nice. You can implement Overloading to provide for different parameter Types:
Friend Function FooBar(n As Integer) As Integer
Friend Function FooBar(n As Int64) As Integer
Friend Function FooBar(n As Short) As Integer
The compiler will pick the function which matches the data type being passed. Internally, they might do whatever based on the Type passed, then call another procedure to perform any stuff common to them all.
There is probably a finite number of types you need it to work with. For instance Font, Point and Rectangle probably make no sense. Even Date is dubious because you cannot do stuff to a date in the same way as with an Int or Long. String is also not likely needed because you can always pass it as FooBar(CInt(someString)) provided it does contain a valid integer or whatever.
You can also use a generic to tell the function what you are passing:
Private Function FooBar(Of T)(parm As T) As Integer
' called as:
ziggy = FooBar(Of Int32)(n)
zoey = FooBar(Of String)(str)
This might even be Private Function FooBar(Of T)(parm As T) As T if the function return varies depending on the parameter Type passed. There are many uses for this (one of which is to avoid passing a param as Object), but as a general purpose way of passing any type you want it is not a good idea: internally you will likely have to have a big If/Else to handle the different types their own way.
Turning off Option Strict is never advisable since all sorts of unwanted type conversions can take place.
In VB.NET, you can use Object as the type but with Option Strict Off. You can pass any kind of parameter in that case.
for more information, refer : https://stackoverflow.com/a/2890023/3660930

Determining variable type in Fortran

In Fortran, is there a way to determine the type of a variable?
A possible use case where the type of a variable would be needed is the following. We pass a variable's type as an argument to a function, to be able to call type-specific code with that function, thus eliminating the need to have separate similar functions for each data type.
Well you might be able to do what you want if you mess about with the KIND intrinsic and POINTERs, but if you are only concerned with the signature of functions and subroutines, leave it to Fortran. If you define
function calc8(arg1)
real(8), intent(in) :: arg1
...
and
function calc4(arg1)
real(4), intent(in) :: arg1
...
in a module, and declare an interface like this
interface calc
module procedure calc8
module procedure calc4
end interface
(Warning, I haven't checked the syntax in detail, that's your responsibility.)
then Fortran will match the call to the right version of the function. Sure, you have to write both versions of the function, but that's really the Fortran 95 way of doing it. This can be quite tedious, I tend to write a generic version and run a sed script to specialise it. It's a bit of a kludge but it works.
If the code of the function is identical apart from the kind of the arguments I sometimes write the function for real(8) (or whatever) and write a version for real(4) which calls the real(8) version wrapped in type conversions.
In Fortran 2003 there are improved ways of defining polymorphic and generic functions, but I haven't really got my head around them yet.
Yes, there are two ways.
The first way does requires you to write separate functions or subroutines for each variable type, but you don't have to call different functions. This may or may not be close enough to what you want. You write the separate routines, then to write an interface to create a generic function or subroutine wrapping these specific subroutines. You don't have to pass the variable type, or do anything special in your call -- it is all done via the declaration and automatically by the compiler from the variable itself, as long as the variables are different enough that the compiler can distinguish them (there are rules about what is required). This is similar to how intrinsic functions work -- you can call sin with a real argument, a double precision real argument or a complex argument and the compiler calls the correct actual function and returns the matching result. High Performance Mark sketched a solution along these lines. For another question, I posted a working example, where the distinguishing feature of the variables was array rank: how to write wrapper for 'allocate'. An advantage of this method is that it is widely support by Fortran compilers.
In Fortran 2003/2008 there are extensive object oriented features. Quoting "Fortran 95/2003 explained" by Metcalf, Reid and Cohen, "To execute alternative code depending on the dynamic type of a polymorphic entity and to gain access to the dynamic parts, the select type construct is provided." The select type statement is a bit similar to a select case statement. This is support by fewer compilers. Again, you don't have to pass the type, since the compiler can figure it you from the variable itself. But it has to be a polymorphic type... Both Intel ifort and gfortran list select type and polymorphic datatypes as supported -- the later with some experimental aspects in gfortran (http://gcc.gnu.org/wiki/Fortran2003). These are recent additions to these compilers.
Here is a piece of code that determines what the type of something is. The action is trivial but you should be able to extend it to your use case.
module element_to_datatype
use iso_fortran_env
use mpi_f08
implicit none
contains
function get_element_datatype(element) result(datatype)
class(*), intent(in) :: element
type(MPI_Datatype) :: datatype
select type(element)
! REAL types
type is ( real(kind=REAL32) )
datatype = MPI_REAL4
type is ( real(kind=REAL64) )
datatype = MPI_REAL8
! COMPLEX types
type is ( complex(kind=REAL32) )
datatype = MPI_COMPLEX8
type is ( complex(kind=REAL64) )
datatype = MPI_COMPLEX16
! INTEGER types
type is ( integer(kind=INT8) )
datatype = MPI_INTEGER1
type is ( integer(kind=INT16) )
datatype = MPI_INTEGER2
type is ( integer(kind=INT32) )
datatype = MPI_INTEGER4
type is ( integer(kind=INT64) )
datatype = MPI_INTEGER8
! OTHER types
type is ( logical )
datatype = MPI_LOGICAL
end select
end function
end module element_to_datatype
A previous answer shows how to do this with interfaces, so I won't repeat that.

What is the definition of ":=" in vb

I came across some sample code in VB.Net which I have some experience with and kinda having a duh moment figuring out the meaning of :=.
RefreshNavigationImages(bForward:=True, startIndex:=-1)
The sig for this method is RefreshNavigationImages(boolean, int). Is this a default value if null? Like "bIsSomething ?? false"?
Tried to bing/google but they just don't like searching for operators especially if it's only 2 chars.
They are named parameters. They let you specify values for arguments in function calls by name rather than order.
The := indicates the use of named parameters. Rather than relying on the order of the parameters in the method declaration, named parameters allow you to specify the correlation of parameters to values by specifying the name of the parameter.