Bindings for lightuserdata.

#6 Merged
Repository
jas43
Branch
default
Repository
haraldkl
Branch
default
Author
  1. jas43
Reviewers
Description

This exposes (part of) the lightuserdata API to Fortran.

This is useful for passing Fortran state back and forth between Lua and Fortran rather than relying upon global Fortran state.

Example:

program f03_lua_inp

    use aotus_module, only: open_config_file
    use flu_binding
    implicit none

    type test_t
        integer :: a, b
    end type test_t
    type(test_t), target :: t

    type(flu_State) :: L
    integer :: err
    character(255) :: err_string = ''

    t = test_t(-1,5)

    ! Open new lua state.
    L = fluL_newstate()

    ! Let lua know what fortran routines it can call directly.
    call register_interfaces(L)

    ! Now run the lua input script and act accordingly.
    call open_config_file(L, "inp.lua", err, err_string)
    if (err /= 0) then
        write (6,*) "Error reading lua script: "//trim(err_string)
        stop
    end if

    call flu_close(L)

    contains

        subroutine register_interfaces(L)

            type(flu_State), intent(inout) :: L

            call flu_register(L, "get_struct", get_struct)
            call flu_register(L, "print_struct", print_struct)

        end subroutine register_interfaces

        function get_struct(state) result(npush) bind(c)

            use, intrinsic :: iso_c_binding, only: c_ptr, c_loc

            integer :: npush
            type(c_ptr), value :: state
            type(flu_State) :: L
            type(c_ptr) :: ptr

            L = flu_copyptr(state)
            ptr = c_loc(t)
            call flu_pushlightuserdata(L, ptr)
            npush = 1

        end function get_struct

        function print_struct(state) result(npush) bind(c)

            use, intrinsic :: iso_c_binding, only: c_ptr, c_loc, c_f_pointer
            use aot_top_module, only: aot_top_get_val

            integer :: npush
            type(c_ptr), value :: state
            type(flu_State) :: L
            type(test_t), pointer :: tptr
            type(c_ptr) :: ptr
            integer :: err

            L = flu_copyptr(state)

            write (6,*) 'is lightuserdata?', flu_islightuserdata(L, flu_gettop(L))
            call aot_top_get_val(ptr, err, L)
            if (err == 0) then
                call c_f_pointer(ptr, tptr)
                write (6,*) 't', tptr
            end if

            npush = 0

        end function print_struct

end program f03_lua_inp

and the script inp.lua:

t = get_struct()
print_struct(t)

produces the output:

 is lightuserdata? T
 t          -1           5

Comments (1)